Reputation: 13
Button I made in sublayout is not working. I want my button_sub to work when I click. I think there is problem with layer inflater, but I still don't get it
final View addedView =inflater.inflate(R.layout.sublayout,null);
How can I modify my code?
This is my MainActivity class
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button3by3 = findViewById(R.id.button_3by3);
container=findViewById(R.id.container);
button3by3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
LayoutInflater inflater =(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View addedView =inflater.inflate(R.layout.sublayout,null);
container.addView(addedView);
}
});
}
Here is my main activity xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:layout_editor_absoluteX="154dp"
tools:layout_editor_absoluteY="138dp">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Toast"
android:id="@+id/button_sub"/>
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
and lastly my sublayout activity:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sublayout);
btn_sub=findViewById(R.id.button_sub);
textView = findViewById(R.id.textView);
btn_sub.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(subAction.this, "Hello", Toast.LENGTH_SHORT).show();
textView.setText("HELLLLLOOOO");
}
});
}
Upvotes: 0
Views: 481
Reputation: 23
You may try doing inflating operations inside onCreateView or maybe you're only problem is
using getSystemService directly without using getContext so first creating Context context
and then using getSystemService on this context would be another option.
In the activity you may try;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
inflater =(LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View addedView = inflater.inflate(R.layout.sublayout,container,false);
button3by3 = addedView.findViewById(R.id.button_3by3);
button3by3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//related code comes here
}
});
return addedView;
}
}
PS: You may also try these inside a fragment.
Upvotes: 2