您好,登錄后才能下訂單哦!
在Fragment中使用Button并設置布局約束,你需要遵循以下步驟:
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button_example"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click me!" />
</androidx.constraintlayout.widget.ConstraintLayout>
findViewById()
方法獲取Button實例。然后,為Button設置點擊事件監聽器。對于Java:
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
public class ExampleFragment extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
ConstraintLayout fragmentView = (ConstraintLayout) inflater.inflate(R.layout.fragment_example, container, false);
Button buttonExample = fragmentView.findViewById(R.id.button_example);
buttonExample.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Handle button click event
}
});
return fragmentView;
}
}
對于Kotlin:
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.fragment.app.Fragment
class ExampleFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val fragmentView = inflater.inflate(R.layout.fragment_example, container, false) as ConstraintLayout
val buttonExample: Button = fragmentView.findViewById(R.id.button_example)
buttonExample.setOnClickListener {
// Handle button click event
}
return fragmentView
}
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。