NullPointerException in button onClick in fragment [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I have two buttons and an EditText in a fragment. When I click the addMusicButton, I want it to disappear and make newMusic(my EditText) and confirmAddButton appear. If I only change the visibility of the addMusicButton in the onClick method, it works, but if I try to change the visibility of newMusic or confirmAddButton in the onClick method, it gives me this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setVisibility(int)' on a null object reference
and my app crashes. I don't understand why it's saying my button is null because I initialized it right before I changed the visibility in the onClick method(the same thing happens if I try to change the visibility of the EditText). I am able to change the visibility of both my buttons and my EditText in onCreate, just not in onClick. I thought it might be because newMusic and confirmAddButton were in a different linear layout from addMusicButton, so I tried moving them all to one layout and it still gave me the same error.
This is my XML file:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="#+id/addMusicButton"
android:layout_width="match_parent"
android:layout_height="109dp"
android:layout_weight="1"
android:text="#string/add_music" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="109dp"
android:layout_weight="1"
android:orientation="horizontal">
<EditText
android:id="#+id/newMusic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:width="330dp"
android:autofillHints=""
android:ems="10"
android:gravity="left|center_vertical"
android:inputType="textAutoComplete" />
<Button
android:id="#+id/confirmAddButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center|center_vertical"
android:text="#string/add" />
</LinearLayout>
<ScrollView
android:layout_width="match_parent"
android:layout_height="585dp"
android:layout_weight="1">
<LinearLayout
android:id="#+id/musicLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" />
</ScrollView>
</LinearLayout>
And my fragment code
public class MusicFragment extends Fragment implements View.OnClickListener {
private MusicViewModel musicViewModel;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
musicViewModel = ViewModelProviders.of(this).get(MusicViewModel.class);
View root = inflater.inflate(R.layout.fragment_music, container, false);
Button addMusicButton = root.findViewById(R.id.addMusicButton);
EditText newMusic = root.findViewById(R.id.newMusic);
Button confirmAddButton = root.findViewById(R.id.confirmAddButton);
newMusic.setVisibility(View.GONE);
confirmAddButton.setVisibility(View.GONE);
addMusicButton.setOnClickListener(this);
confirmAddButton.setOnClickListener(this);
return root;
}
#Override
public void onClick(View view) {
Button addMusicButton = view.findViewById(R.id.addMusicButton);
Button confirmAddButton = view.findViewById(R.id.confirmAddButton);
EditText newMusic = view.findViewById(R.id.newMusic);
switch (view.getId()) {
case R.id.addMusicButton:
confirmAddButton.setVisibility(View.VISIBLE);
newMusic.setVisibility(View.VISIBLE);
addMusicButton.setVisibility(View.GONE);
break;
case R.id.confirmAddButton:
(...)
break;
}
}
}

Instead of using separate initialization, you have to use only one initialization which is at onCreateView method only. And declare Button and EditText outside the method.
Try this code:
Button addMusicButton, confirmAddButton ;
EditText newMusic;
In OnCreateView method :
addMusicButton = root.findViewById(R.id.addMusicButton);
newMusic = root.findViewById(R.id.newMusic);
confirmAddButton = root.findViewById(R.id.confirmAddButton);
addMusicButton.setOnClickListener(this);
confirmAddButton.setOnClickListener(this);
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.addMusicButton:
confirmAddButton.setVisibility(View.VISIBLE);
newMusic.setVisibility(View.VISIBLE);
addMusicButton.setVisibility(View.GONE);
break;
case R.id.confirmAddButton:
(...)
break;
}
}

Why your again initialize Button addMusicButton , Button confirmAddButton ,EditText newMusic that is why your getting null pointer exception so please remove onclick initialize Button , EditText

Declare the view(Button, EditText, TextView...) outside onCreateView method if you want to perform some operations. So, try the below code.
public class MusicFragment extends Fragment implements View.OnClickListener {
private MusicViewModel musicViewModel;
private Button addMusicButton, confirmAddButton;
private EditText newMusic;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
musicViewModel = ViewModelProviders.of(this).get(MusicViewModel.class);
View root = inflater.inflate(R.layout.fragment_music, container, false);
addMusicButton = root.findViewById(R.id.addMusicButton);
newMusic = root.findViewById(R.id.newMusic);
confirmAddButton = root.findViewById(R.id.confirmAddButton);
newMusic.setVisibility(View.GONE);
confirmAddButton.setVisibility(View.GONE);
addMusicButton.setOnClickListener(this);
confirmAddButton.setOnClickListener(this);
return root;
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.addMusicButton:
confirmAddButton.setVisibility(View.VISIBLE);
newMusic.setVisibility(View.VISIBLE);
addMusicButton.setVisibility(View.GONE);
break;
case R.id.confirmAddButton:
(...)
break;
}
}
}

Related

Attempt to invoke virtual method 'void android.widget.ImageView.setVisibility(int)' on a null object reference [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
I have 2 layout files (activity_test.xml) and (content.xml) and one java file (ActivityTest.java)
ActivityTest.java set its content layout from (activity_test.xml) as shown
ActivityTest.java
#Override
protected void onCreate(Bundle savedInstanceState) {
.....................
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
}
activity_test.xml contains a recyclerView as shown
activity_test.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"
tools:context=".ActivityTest">
............
some views
...........
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/recycler_view2"
android:layout_marginTop="30dp"
android:layout_alignParentBottom="true"
android:scrollbars="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0"
/>
I have a RecyclerViewAdapter that inflates the (content.xml) layout as shown
RecyclerViewAdapter
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {
.............
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.content, parent, false);
return new RecyclerViewAdapter.MyViewHolder(itemView);
}
}
Here is the content.xml
content.xml
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".TestActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
...........
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/save"
android:src="#drawable/outline_share_black_48dp"
android:layout_toLeftOf="#+id/savePhoto"
android:layout_marginTop="5dp"
android:layout_marginRight="20dp"
android:clickable="true"
android:onClick="saveIntent"
/>
The problem - Setting a click Listener on the ImageView above with the id(save) throws that error.
ClickEvents such as - OnClickListener, OnTouchLlistener, setVisibility all throws the error - "Attempt to invoke virtual method 'void android.widget.ImageView.setVisibility(int)' on a null object reference"
e.g
MainActivity.java
..........
private ImageView save_icon;
..........
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
.............
save_icon = findViewById(R.id.save);
........
public void saveIntent(View view){
if(view.getId() == R.id.savePhotoIcon){
save_icon.setImageResource(R.drawable.outline_bookmark_black_48dp);
}
}
I want to change the image src of the ImageView to another Image onClick
I tried doing this without xml - (android:Clickable and android:OnClick) but still throwing thesame error.
Most likely the id(save) in content.xml is returning a null value because it wasnt't used as the setContentView layout in onCreate in MainActivity.Java file.
When I tried thesame thing on a view from (activity_test.xml), it works.
Although, Actions such as - Displaying a toast message, New Intent all works.
e.g
public void saveIntent(View view){
Intent intent = new Intent(ActivityTest.this, AnotherActivity.class);
startActivity(intent);
}
This is because you're creating the view holders at run time using layout template, and you call the view holder before the view shows on screen. For this, you have to implement it in onBindViewHolder:
public void onBindViewHolder(MyViewHolder holder, int position)
{
ImageView imgView=holder.itemview.findViewById(R.id.save);
imgView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Code here executes when user click on save
}
});
}

Opening a dialog box inside adapter returning null values

I have been trying to get this to work without success for about 10 hours now, I have looked all over stack overflow. I am trying to get a simple dialog box to appear and handle some simple input.
It has a TextView as a title, EditText as a input field, and two button continue with the operation or cancel.
For some reason, no matter what I do, I cannot seem to be able to reference ANY view inside my shopping_dialogue xml layout. It gives me this error:
java.lang.NullPointerException: Attempt to invoke virtual method
'void android.widget.TextView.setText(java.lang.CharSequence)' on a
null object reference
I have tried to add an onClick event to the button to see if that works, when I try to reference the button inside the onClick method it gives me the same error. I am using a fragment to do this.
shopping_dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/shoppingDialogTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Edit Shopping List Name" />
<EditText
android:id="#+id/shoppingDialogEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="30"
android:inputType="textPersonName"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<Button
android:id="#+id/shoppingDialogOk"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button" />
<Button
android:id="#+id/shoppingDialogCancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="k"
android:text="Button" />
</LinearLayout>
shopping_list_row.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
card_view:cardCornerRadius="4dp"
android:id="#+id/shoppingList_card_view"
android:layout_margin="10dp"
android:layout_height="200dp">
<LinearLayout
android:id="#+id/shoppingListParent"
android:layout_gravity="center"
android:layout_width="match_parent"
android:orientation="vertical"
android:gravity="center"
android:layout_height="match_parent">
<TextView
android:id="#+id/shoppingName"
android:layout_width="wrap_content"
android:gravity="center"
android:textSize="25sp"
android:textColor="#FFF"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/shoppingDate"
android:layout_width="wrap_content"
android:gravity="center"
android:textSize="25sp"
android:textColor="#FFF"
android:layout_height="wrap_content" />
</LinearLayout>
</androidx.cardview.widget.CardView>
fragment_shopping_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/shoppingList_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
ShopingAdapter.java
public class ShoppingAdapter extends RecyclerView.Adapter<ShoppingAdapter.ShoppingViewHolder> {
private List<ShoppingData> shoppingList;
private Context context;
public ShoppingAdapter(List<ShoppingData> shoppingList, Context context){
this.shoppingList = shoppingList;
this.context = context;
}
#NonNull
#Override
public ShoppingViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i){
View itemView = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.shopping_list_row, viewGroup, false);
return new ShoppingViewHolder(itemView);
}
#Override
public void onBindViewHolder(ShoppingViewHolder viewHolder, int i){
ShoppingData data = shoppingList.get(i);
Random k = new Random();
int color = Color.argb(255,k.nextInt(255),k.nextInt(255),k.nextInt(255));
viewHolder.parent.setBackgroundColor(color);
viewHolder.shoppingName.setText(data.getName());
viewHolder.shoppingDate.setText(data.getDate());
viewHolder.shoppingName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder1 = new AlertDialog.Builder(v.getContext());
builder1.setCancelable(true);
builder1.setView(R.layout.shopping_dialog);
AlertDialog alert = builder1.create();
/*
EditText text = v.findViewById(R.id.shoppingDialogEditText);
text.setText("Some Text");
This causes a null object reference
*/
alert.show();
}
});
}
#Override
public int getItemCount(){return shoppingList.size();}
public class ShoppingViewHolder extends RecyclerView.ViewHolder{
private TextView shoppingName, shoppingDate;
private LinearLayout parent;
public ShoppingViewHolder(View itemView){
super(itemView);
parent = itemView.findViewById(R.id.shoppingListParent);
shoppingName = itemView.findViewById(R.id.shoppingName);
shoppingDate = itemView.findViewById(R.id.shoppingDate);
}
}
}
ShoppingFragment.java
public class ShoppingFragment extends Fragment {
private RecyclerView recyclerView;
private ShoppingAdapter shoppingAdapter;
private List<ShoppingData> shoppingList = new ArrayList<>();
#NonNull
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState){
shoppingList.add(new ShoppingData("k","12/12/12"));
shoppingList.add(new ShoppingData("k","12/12/12"));
shoppingList.add(new ShoppingData("k","12/12/12"));
shoppingList.add(new ShoppingData("k","12/12/12"));
shoppingList.add(new ShoppingData("k","12/12/12"));
shoppingList.add(new ShoppingData("k","12/12/12"));
View rootView = inflater.inflate(R.layout.fragment_shopping_list, container, false);
recyclerView = rootView.findViewById(R.id.shoppingList_recycler_view);
shoppingAdapter = new ShoppingAdapter(shoppingList, getActivity());
RecyclerView.LayoutManager manager = new GridLayoutManager(getActivity(), 2);
recyclerView.setLayoutManager(manager);
recyclerView.setAdapter(shoppingAdapter);
return rootView;
}
public void k(View view){ //the click listern that causes a null object reference when referencing the button
Button button = view.findViewById(R.id.shoppingDialogOk);
button.setText("k");
}
}
ShoppingData.java
package com.uhcl.recipe5nd.helperClasses;
public class ShoppingData {
private String name;
private String date;
public ShoppingData(String name, String date){
this.name = name;
this.date = date;
}
public String getDate(){
return this.date;
}
public String getName(){
return this.name;
}
}
Everything works fine until I try to reference anything inside shopping_dialog.xml.
If you look at my shopping adapter class, what I am trying to do is to add an onClick listener to the "shoppigName" text view inside my onBindViewHolder method. This works, but when I try to reference the shoppingDialogEditText, it causes the app the crash and give me that error.
Like I mentioned I also tried adding a click event method k to a button inside shopping_dialog.xml, and implemented it inside my fragment class to see if that would work, but it still causes the same error.
viewHolder.shoppingName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View dailogView = LayoutInflater.from(mContext).inflate(R.layout.shopping_dialog, null);
AlertDialog.Builder builder1 = new AlertDialog.Builder(v.getContext());
builder1.setCancelable(true);
builder1.setView(dailogView);
AlertDialog alert = builder1.create();
EditText text = dailogView.findViewById(R.id.shoppingDialogEditText);
text.setText("Some Text");
alert.show();
}
});
The view your using to the find the edittext is not the view of that dialog box, therefore it's throwing null pointer.
You are using a wrong view to find the editText. It is not the view of dialog box. It is the view of the item which is being clicked rather than dialog box.
Use this
viewHolder.shoppingName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View dailogView =
LayoutInflater.from(mContext).inflate(R.layout.shopping_dialog, null);
AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
builder.setCancelable(true);
builder.setView(dailogView);
AlertDialog alert = builder.create();
EditText text = dailogView.findViewById(R.id.shoppingDialogEditText);
text.setText("Shopping Dialog Text");
alert.show();
}
});
}

On Create View in Fragment, getting null pointer exception when getting a string from EditText

I am getting a null pointer exception when getting a string from EditText. Is it because I am using a fragment, should I use an async task? I have no idea why this is happening. I get the error when I add the s1 = text1.getText().toString(); line.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.tromto.analyzevalue.MainActivity$PlaceholderFragment" >
<EditText
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="numberDecimal" >
<requestFocus />
</EditText>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
public class MyFragment1 extends Fragment {
EditText text1;
Button button1;
String s1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
Toast t = Toast.makeText(getActivity(), "Section 1", Toast.LENGTH_LONG);
t.show();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.fragment_main, container, false);
text1 = (EditText)getActivity().findViewById(R.id.editText1);
s1 = text1.getText().toString();
return v;
}
}
You are trying to findViewById from the Fragment's parent Activity. Instead, you should findViewById in your Fragment's View.
use:
text1 = (EditText) v.findViewById(R.id.editText1);
instead of:
text1 = (EditText)getActivity().findViewById(R.id.editText1);
I just answered similar question. You have empty value in EditText1 on start. Do not use solutions as this on create, or fill some text inside if you must.

Relative Layout All Childs Clickable

This Question Is Pretty Silly to ask but out, but i Would like to know how it Works?
I had a Relative Layout with 2 ImageViews as Child having separate clickListner instances. One above Another, of same Size and Attributes.
Overlaps Each other. Both having Different images.
Question is When i click on one image both ImageView Click listners are Called.
Or if i disable the Click on ImageView Top, The ImageView Below Still Works, I was Clicking on Image View Above though. How it is I'ts Getting callback from both.
I Just Want to know How it works? not The code, i do not have any issue writing code for clickListners Whether only one Working or Both.
<RelativeLayout
----
---
>
<ImageView
---
---<!--Child 1-->
<ImageView
---
---<!--Child 2-->
<RelativeLayout/>
Taken from here:
if you are working with just one clicklistener, you can do:
View.OnClickListener myOnlyhandler = new View.OnClickListener() {
public void onClick(View v) {
switch(v.getId()) {
case R.id.b1:
// it was the first button
break;
case R.id.b2:
// it was the second button
break;
}
}
}
Use ImageButton
Layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ImageButton
android:id="#+id/imageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="#string/content"
android:src="#drawable/ic_launcher" />
</LinearLayout>
Activity class
public class MainActivity extends Activity {
ImageButton imgButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addButtonListener();
}
public void addButtonListener() {
imgButton = (ImageButton) findViewById(R.id.imageButton);
imgButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this,"ImageButton is working!", Toast.LENGTH_SHORT).show();
}
});
}
}
Give this to your parent layout
android:context="Yourclasshere"
then give this to your image view
android:onclick="onclick"
and then implement the on click listener or make the method like Vitly A make above

How to get instance of view's parent fragment:

I have a fragment with an XML layout file. in it I have an 2 clickable ImageViews.
for each ImageView I set an onClick method for example: android:onClick="commentFragmentRemoveOnClick".
In the FragmentActivity (The Activity no the Fragment) I defined it this way:
public void commentFragmentRemoveOnClick(View v)
{
}
No this Fragment is of type CommentFragment and it has a public void getFragmentTag()method
to get it's tag that I save in earlier time. I need to get an instance of the fragment in which the image was clicked to get it's tag.
I tried:
((CommentFragment)v).getParentFragment().getFragmentTag();
and:
((CommentFragment)v).getParent().getFragmentTag();
but eclipse gives me error on both of them, how is this done properly?
To make it more clear this is my CommentFragment:
public class CommentFragment extends Fragment {
private final static String TAG = CommentFragment.class.getSimpleName();
private String fragmentTag;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.comment_fragment_layout,
container, false);
Bundle bundle = getArguments();
String text = bundle.getString("comment");
String fullUser = bundle.getString("user");
String user = fullUser.substring(0, fullUser.indexOf("#"));
String at = bundle.getString("at");
TextView tvCmment = (TextView) rootView.findViewById(R.id.tvComment);
TextView tvUser = (TextView) rootView.findViewById(R.id.tvUser);
TextView tvAt = (TextView) rootView.findViewById(R.id.tvDate);
tvCmment.setText(text);
tvUser.setText(user);
tvAt.setText(at);
return rootView;
}
public void setText(String item)
{
TextView view = (TextView) getView().findViewById(R.id.tvComment);
view.setText(item);
}
public void setFragmentTag(String tag)
{
this.fragmentTag = tag;
}
public String getFragmentTag()
{
return this.fragmentTag;
}
}
and the layout file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/llCommentContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="#drawable/try2">
<TextView
android:id="#+id/tvUser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/tvComment"
android:layout_alignParentTop="true"
android:background="#color/my_gray"
android:text="demo"
android:textStyle="bold"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:textColor="#color/my_even_darker_gray" />
<TextView
android:id="#+id/tvComment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/tvDate"
android:padding="5dp"
android:text="This task is described in more details if you click on it."
android:textColor="#color/my_even_darker_gray" />
<TextView
android:id="#+id/tvAt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:paddingRight="5dp"
android:textColor="#color/my_even_darker_gray"
android:layout_toRightOf="#+id/tvUser"
android:background="#color/my_gray"
android:text="at" />
<TextView
android:id="#+id/tvDate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/tvAt"
android:layout_alignBottom="#+id/tvAt"
android:layout_toRightOf="#+id/tvAt"
android:background="#color/my_gray"
android:text="12/02"
android:textColor="#color/my_even_darker_gray" />
<ImageView
android:id="#+id/iEdit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/tvComment"
android:layout_marginRight="4dp"
android:clickable="true"
android:contentDescription="#drawable/add_comment_button"
android:onClick="commentFragmentEditOnClick"
android:src="#drawable/add_comment_button" />
<ImageView
android:id="#+id/iRemove"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/iEdit"
android:layout_toRightOf="#+id/iEdit"
android:layout_marginRight="4dp"
android:clickable="true"
android:contentDescription="#drawable/add_comment_button"
android:onClick="commentFragmentRemoveOnClick"
android:src="#drawable/add_comment_button" />
</RelativeLayout>
I would love for a little assistance.
Thanks.
I have a general advice for you that would solve your problem and help you in the future -
don't use android:onClick in the xml file, use setOnClickListener in the code itself - need to avoid mixing your views with other parts of the app as much as possible.
Try to keep the Fragment independent of its activity.
If the image is part of the fragment, why does the listener is part of the FragmentActivity?
Use setOnClickListener in the fragment itself, and you might be able to use this Framgent in other pats of the app without being depended on the Activity.
It would also solve your problem of identifying the fragment in which the image was clicked.
v is not an instance of Fragment, that's why Eclipse does not like your code. If you want the instance of a fragment you have to use the FragmentManager and one of its findFragmentByXXX methods.
To get the instance of the fragment that the ImageView was clicked in I did the following:
in the Fragment I set two onClickListeners for both of the images like this:
iEdit = (ImageView)rootView.findViewById(R.id.iEdit);
iEdit.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Log.d(TAG, "pressed edit button");
((PicturesAndCommentsActivity) getActivity()).commentFragmentEditOnClick(fragmentTag);
}
});
iRemove = (ImageView)rootView.findViewById(R.id.iRemove);
iRemove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Log.d(TAG, "pressed remove button");
((PicturesAndCommentsActivity) getActivity()).commentFragmentRemoveOnClick(fragmentTag);
}
});
and in the fragment activity I defined those two methods like this:
public void commentFragmentRemoveOnClick (String tag)
{
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.remove(fragmentManager.findFragmentByTag(tag)).commit();
}
for removing the fragment, and Now I'm working on editing the fragment.

Categories

Resources