我有一個Fragment類,它動態地創建一個按鈕的網格。然後在顯示網格的主活動中創建該片段的一個實例。這裏是我的代碼:如何檢測一個片段內的動態創建的按鈕被點擊,從活動?
Grid.java
public class Grid extends Fragment {
LinearLayout myLayout;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myLayout = new LinearLayout(getActivity());
LayoutParams lparams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
myLayout.setLayoutParams(lparams);
myLayout.setOrientation(LinearLayout.VERTICAL);
for (int i = 0; i < 4; i++) {
LinearLayout row = new LinearLayout(getActivity());
LayoutParams rowParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
row.setLayoutParams(rowParams);
for (int j = 0; j < 4; j++) {
final Button btnTag = new Button(getActivity());
LayoutParams btnParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
btnTag.setLayoutParams(btnParams);
btnTag.setText(" " + (j + 1 + (i * 4)));
btnTag.setId(j + 1 + (i * 4));
row.addView(btnTag);
}
myLayout.addView(row);
}
return myLayout;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_mainactivity);
Grid grid = new Grid();
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.grid, grid);
transaction.commit();
}
}
而且除了這裏是我的content_mainactivity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/content_mainactivity"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.example.owner.tables.MainActivity"
tools:showIn="@layout/activity_mainactivity">
<FrameLayout
android:layout_width="320dp"
android:layout_height="320dp"
android:id="@+id/grid"
android:layout_centerHorizontal="true">
</FrameLayout>
</RelativeLayout>
所以我的問題是,我該如何檢測是否和哪個按鈕在活動的片段中被點擊?或者如果我可以在片段中做到這一點,如何將信息傳遞給活動?
我對setEleListener有些困惑嗎?這是一個需要在Fragment中實現的方法,還是它已經屬於Fragment對象?此外,片段還需要具有「MyGridInterface gListener;」格式的字段? –
只需將偵聽器設置爲MainActivity即可監聽片段到事件的事件 –