I am trying to get the text from an EditText in an XML I have:`
this is my XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/background"
android:orientation="vertical" >
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_marginLeft="30dp"
android:layout_marginTop="15dp"
android:text="Name"
android:textColor="#color/accent_red"
android:textSize="25sp" />
<EditText
android:id="#+id/editContactName"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#drawable/border"
android:ems="10"
android:hint="Name"
android:imeOptions="actionNext"
android:inputType="textPersonName"
android:paddingLeft="30dp"
android:paddingRight="30dp"
android:textSize="30sp" />
</LinearLayout>
</ScrollView>
</LinearLayout>
This is my class classed SHConfigureContactFragment
public class SHConfigureContactFragment extends Fragment{
private EditText name;
private EditText description;
private EditText primaryNumber;
private EditText secondaryNumber;
private EditText email;
private EditText skype;
private Byte[] photo;
private Boolean isDualPane;
private FragmentManager fragmentManager;
private SHContactMenuFragment menuFragment;
private SHConfigureContactFragment contactFragment;
private DatabaseControllerLibrary databaseController;
private Contact contact;
public int selectedIndex;
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if(savedInstanceState != null) {
this.selectedIndex = savedInstanceState.getInt("SELECTED_INDEX");
this.contact = (Contact) savedInstanceState.getSerializable("CONTACT");
}
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
super.onCreateView(inflater, container, savedInstanceState);
View rootView = inflater.inflate(R.layout.sh_fragment_contact_edit, container, false);
return rootView;
}
private void setupTextFieldsByContact(Contact contact) {
name = (EditText) findViewById(R.id.editContactName);
// description = (EditText) findViewById(R.id.editContactDescription);
// primaryNumber = (EditText) findViewById(R.id.editContactPrimaryNumber);
// secondaryNumber = (EditText) findViewById(R.id.editContactSecondaryNumber);
// email = (EditText) findViewById(R.id.editContactEmail);
// skype = (EditText) findViewById(R.id.editContactSkype);
if (contact != null) {
name.setText(contact.getName());
description.setText(contact.getDescription());
primaryNumber.setText(contact.getPrimaryNumber());
secondaryNumber.setText(contact.getSecondaryNumber());
email.setText(contact.getEmail());
skype.setText(contact.getSkype());
}
}
}
It seems as though I cannot callfindViewById(R.id.editContactName)because I am not extending an Activity. I have looked at various posts here but have not found a solution. I thought about using getText() method, but that does not let me get specific EditText elements. I hope to have many editable fields that is why I need to get by the specific ID's
You can access the view inflated in onCreateView(...) by calling getView(). You can use the following code anytime after onCreateView(...):
getView().findViewById(R.id.editContactName)
Here's what I would do inside the fragment:
EditText mName, mDescription, mPrimaryNumber, mSecondaryNumber, mEmail, mSkype;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// no need for super here, the default fragment has no layout
// inflate the layout in this method
View rootView = inflater.inflate(R.layout.sh_fragment_contact_edit, container, false);
return rootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// save views as variables in this method
// "view" is the one returned from onCreateView
mName = (EditText) view.findViewById(R.id.editContactName);
mDdescription = (EditText) view.findViewById(R.id.editContactDescription);
mPrimaryNumber = (EditText) view.findViewById(R.id.editContactPrimaryNumber);
mSecondaryNumber = (EditText) view.findViewById(R.id.editContactSecondaryNumber);
emEail = (EditText) view.findViewById(R.id.editContactEmail);
mSkype = (EditText) view.findViewById(R.id.editContactSkype);
}
private void setupTextFieldsByContact(Contact contact) {
// call this method anytime the contact changes without having to find views again
if (contact != null) {
mName.setText(contact.getName());
mDescription.setText(contact.getDescription());
mPrimaryNumber.setText(contact.getPrimaryNumber());
mSecondaryNumber.setText(contact.getSecondaryNumber());
mEmail.setText(contact.getEmail());
mSkype.setText(contact.getSkype());
}
}
In the onCreateView method, do this:
name = (EditText) rootView.findViewById(R.id.editContactName);
Hope it will help fix your problem.
Related
i have an xml file that contains a reusable layout that i want to be added when the user clicks a button.
inputs.xml
<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="wrap_content">
<Button
android:id="#+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/add"
android:textColor="#color/text_color_blue"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="#+id/edittext"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="#string/amount"
android:textColor="#color/text_color_blue"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/btn"
app:layout_constraintStart_toEndOf="#+id/textview"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/textview"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:gravity=""
android:text="#string/category"
android:textColor="#color/text_color_blue"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
This layout is loaded into a fragment budgetFragment.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.dashboard.fragments.BudgetFrag">
<LinearLayout
android:id="#+id/budget_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="17dp"
android:orientation="vertical">
</LinearLayout>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/floating"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|bottom"
android:layout_margin="10dp"
app:srcCompat="#android:drawable/ic_input_add"/>
</FrameLayout>
the elements get loaded as I need them to but only one problem, all the elements have the same id which comes from the last element loaded.
private BudgetViewModel mViewModel;
private LinearLayout layout = null;
private TextView textView;
private Button button;
private EditText editText;
private ViewGroup viewGroup;
private View viewer;
private LayoutInflater layoutInflater;
private static String TAG = "BudgetFrag :: ";
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.bugdet_fragment, container, false);
viewGroup = container;
return v;
}
public int findUnusedId(LinearLayout layout) {
int fID = 0;
while (layout.findViewById(++fID) != null) ;
return fID;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mViewModel = ViewModelProviders.of(this).get(BudgetViewModel.class);
// TODO: Use the ViewModel
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
FloatingActionButton add_elements = view.findViewById(R.id.floating);
layout = view.findViewById(R.id.budget_layout);
add_elements.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View view = getDialog(getActivity(), layout);
layout.addView(view);
}
});
}
public View getDialog(Context context, final LinearLayout layout) {
layoutInflater = LayoutInflater.from(getContext());
viewer = layoutInflater.inflate(R.layout.buget_input, viewGroup, false);
AlertDialog.Builder b = new AlertDialog.Builder(context);
b.setTitle("Select A Category");
String[] types = {"Food", "Entertainment"};
final String[] selected = {""};
b.setItems(types, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
textView = viewer.findViewById(R.id.textview);
switch (which) {
case 0:
textView.setText("Food");
break;
case 1:
textView.setText("Entertainment");
break;
}
editText = viewer.findViewById(R.id.edittext);
Log.d(TAG, "DialogInterface :: editText :: " + editText.getId());
editText.setId(findUnusedId(layout));
button = viewer.findViewById(R.id.btn);
button.setId(findUnusedId(layout));
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "setOnClickListener :: editText :: " + editText.getId());
if(!editText.getText().toString().trim().isEmpty()){
Toast.makeText(getContext(), "textView.getId()", Toast.LENGTH_LONG).show();
Log.d(TAG, "setOnClickListener :: "+ editText.getText().toString());
}
}
});
dialog.dismiss();
}
}).show();
return viewer;
}
the getDialog method is where the action happens.
All three elements have the same id as the last added input layout elements.
the question is how can i make each added input layout is unique to be able to get the edittext data? how do i change the ids dynamically as the elememnts are being added?
ps. the number of input layout that can be added is infinite.
This could be a tricky method to handle this problem. First create instance variable like
ArrayList<RootView> rootViews = new ArrayList(); Then we have to generate our own ID to each Root View and its corresponding child views and put it inside above rootViews list.
Look below :
LinearLayout linearLayout = findViewById(R.id.linear);
TextView textView = linearLayout.findViewById(R.id.tv);
EditText editText = linearLayout.findViewById(R.id.et);
Button button = linearLayout.findViewById(R.id.btn);
int uniqueLinearLayoutId = View.generateViewId();
int uniqueTextViewId = View.generateViewId();
int uniqueFirstEditTextId = View.generateViewId();
int uniqueBtnId = View.generateViewId();
ArrayList<Integer> childViews = new ArrayList<>();
childViews.add(uniqueTextViewId);
childViews.add(uniqueFirstEditTextId);
childViews.add(uniqueBtnId);
rootViews.add(new RootView(uniqueLinearLayoutId,childViews));
Now we have structured our view id's inside rootViews list. So, now we can identify each view as they have unique id's.
I'm trying to make an app that fetches a book list from an API and displays it on the master list and, upon clicking, it displays the details. It works fine with mobiles, but I can't get it to work with tablets and since there's no error I can't find out where I went wrong.
On tablets it renders as if on a phone instead of rendering the two pane view.
I'm using a single activity with fragments.
"Main" activity:
public class ItemListActivity extends AppCompatActivity {
public static FragmentManager fragmentManager;
private boolean isTwoPane = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_list);
determinePaneLayout();
fragmentManager = getSupportFragmentManager();
if(isTwoPane){
//fragmentManager.beginTransaction().add(R.id.master_dual, new ItemsListFragment()).commit();
fragmentManager.beginTransaction().add(R.id.flDetailContainer, new ItemDetailFragment()).commit();
fragmentManager.beginTransaction().add(R.id.fragmentContainer, new ItemsListFragment()).commit();
} else {
fragmentManager.beginTransaction().add(R.id.fragmentContainer, new ItemsListFragment()).commit();
}
}
private void determinePaneLayout() {
FrameLayout fragmentItemDetail = (FrameLayout) findViewById(R.id.flDetailContainer);
// If there is a second pane for details
if (fragmentItemDetail != null) {
isTwoPane = true;
}
}
Item List Fragment:
public class ItemsListFragment extends Fragment {
private ArrayList<Book> bookList;
private ArrayList<String> bookNames;
private ArrayAdapter<Book> bookArrayAdapter;
private ArrayAdapter<String> bookNamesAdapter;
private ApiInterface apiInterface;
private ListView lvItems;
private static final String bookKey = "newBook";
private static Book nBook;
public ItemsListFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_items_list,
container, false);
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
lvItems = view.findViewById(R.id.lvItems);
bookNames = new ArrayList<>();
//bookNames.add(0, "Gabriel");
apiInterface = ApiClient.getApiClient().create(ApiInterface.class);
Call<ArrayList<Book>> call = apiInterface.getBooks();
call.enqueue(new Callback<ArrayList<Book>>() {
#Override
public void onResponse(Call<ArrayList<Book>> call, Response<ArrayList<Book>> response) {
bookList = new ArrayList<>();
bookList = response.body();
bookArrayAdapter = new ArrayAdapter<>(getContext(),
android.R.layout.simple_list_item_activated_1, bookList);
lvItems.setAdapter(bookArrayAdapter);
}
#Override
public void onFailure(Call<ArrayList<Book>> call, Throwable t) {
}
});
lvItems.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
nBook = bookList.get(i);
if(view.findViewById(R.id.flDetailContainer) != null){
ItemListActivity.fragmentManager.beginTransaction().replace(R.id.flDetailContainer, ItemDetailFragment.newInstance(nBook)).addToBackStack(null).commit();
} else {
ItemListActivity.fragmentManager.beginTransaction().replace(R.id.fragmentContainer, ItemDetailFragment.newInstance(nBook)).addToBackStack(null).commit();
}
}
});
}`
Item Detail Fragment:
public class ItemDetailFragment extends Fragment {
private static final String bookKey = "newBook";
private static Book nBook;
private TextView title;
private TextView isbn;
private TextView currency;
private TextView price;
private TextView author;
public static ItemDetailFragment newInstance(Book book) {
ItemDetailFragment fragment = new ItemDetailFragment();
Bundle args = new Bundle();
args.putSerializable(bookKey, book);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
nBook = (Book)getArguments().getSerializable(bookKey);
Log.v("BundleOK", "BundleOK");
} else {
Log.v("Bundle Nulo", "Bundle nulo");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate view
View view = inflater.inflate(R.layout.fragment_item_detail,
container, false);
// Return view
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
title = view.findViewById(R.id.tvTitle);
isbn = view.findViewById(R.id.tvIsbn);
currency = view.findViewById(R.id.tvCurrency);
price = view.findViewById(R.id.tvPrice);
author = view.findViewById(R.id.tvAuthor);
title.setText(nBook.getTitle());
isbn.setText("ISBN: " + nBook.getIsbn());
currency.setText("Currency: "+ nBook.getCurrency());
price.setText("Price: "+ String.valueOf((long)nBook.getPrice()/100));
author.setText("Autor: "+nBook.getAuthor());
}
XML for dual pane:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:showDividers="middle"
android:baselineAligned="false"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<fragment
android:id="#+id/fragmentItemsList"
android:name="gabrielgomes.studio.com.itemretrieve.ItemsListFragment"
android:layout_height="wrap_content"
android:layout_width="0dp"
android:layout_weight="1"
tools:layout="#layout/fragment_items_list" />
<View android:background="#000000"
android:layout_width="1dp"
android:layout_height="wrap_content"
/>
<FrameLayout
android:id="#+id/flDetailContainer"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="3" />
XML for the Main Activity (Item List Activity)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<FrameLayout
android:id="#+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
XML for the Item Detail Fragment:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/tvTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="110dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:fontFamily="#font/baskervillebt"
android:gravity="center"
android:text="Item Title"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/tvIsbn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tvTitle"
android:layout_centerHorizontal="true"
android:layout_marginTop="44dp"
android:fontFamily="#font/baskervilleitalicbt"
android:text="Item Body"
android:textSize="16sp" />
<TextView
android:id="#+id/tvPrice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tvIsbn"
android:layout_centerHorizontal="true"
android:layout_marginTop="47dp"
android:fontFamily="#font/baskervilleitalicbt"
android:text="Price"
android:textSize="16sp" />
<TextView
android:id="#+id/tvCurrency"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tvPrice"
android:layout_centerHorizontal="true"
android:fontFamily="#font/baskervilleitalicbt"
android:layout_marginTop="44dp"
android:text="Currency"
android:textSize="16sp" />
<TextView
android:id="#+id/tvAuthor"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tvCurrency"
android:fontFamily="#font/baskervilleitalicbt"
android:layout_centerHorizontal="true"
android:layout_marginTop="45dp"
android:text="Author"
android:textSize="16sp" />
</RelativeLayout>
I've been cracking my head for 5 days now, so any help is really appreciated! I tried a number of tutorials and searched SO thoroughly but no go!
Cheers!
I believe you have two copies activity_item_list.xml layout file and one is res/layout/ folder and another one is in res/layout-sw600dp/ folder.
sw600dp --> Screen width above 600dp use this layout else if less than 600dp use default layout file.
And also you make sure keep same attribute ids same in both the layout files.
Red text came out a little small. Here is what it says:
Need to get the background color of the dialog so I can set the background of the "more info" textview to that same color. Need to do this programmatically because color of the dialog is different depending on API level.
Java code:
public class CityDetailDialog extends DialogFragment {
private SharedPreferences sharedPreferences;
private City mCity;
private LinearLayout mCityContainerLayout;
private ImageView mImageFlag;
private TextView mTextCity;
private ImageView mImageCity;
private ImageButton mButtonGoogleMaps;
private ImageButton mButtonWikipedia;
private TextView mMoreInfoTextView;
public CityDetailDialog() {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
sharedPreferences = getActivity().getSharedPreferences("settings", Context.MODE_PRIVATE);
return inflater.inflate(R.layout.dialog_city_detail, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mCity = (City) getArguments().getSerializable("city");
mCityContainerLayout = (LinearLayout) view.findViewById(R.id.container_city_dialog);
mImageFlag = (ImageView) view.findViewById(R.id.flag_image);
mTextCity = (TextView) view.findViewById(R.id.city_name);
mImageCity = (ImageView) view.findViewById(R.id.city_image);
mButtonGoogleMaps = (ImageButton) view.findViewById(R.id.button_google_maps);
mButtonWikipedia = (ImageButton) view.findViewById(R.id.button_wikipedia);
mMoreInfoTextView = (TextView) view.findViewById(R.id.more_info_label);
mImageFlag.setImageResource(ResourceByNameRetriever.getDrawableResourceByName(mCity.
getCountryName(), getActivity()));
mTextCity.setText(ResourceByNameRetriever.getStringResourceByName(mCity.getCityName(),
getActivity()));
Picasso.with(getActivity()).load(mCity.getImageUrl()).into(mImageCity);
mButtonGoogleMaps.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent mapsIntent = new Intent(Intent.ACTION_VIEW);
mapsIntent.setData(Uri.parse("geo:" + mCity.getCoordinates()));
Intent chooser = Intent.createChooser(mapsIntent, getString(R.string.launch_maps));
startActivity(chooser);
}
});
mButtonWikipedia.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent wikiIntent = new Intent(Intent.ACTION_VIEW);
wikiIntent.setData(Uri.parse(mCity.getWikiUrl()));
Intent chooser = Intent.createChooser(wikiIntent, getString(R.string.launch_browser));
startActivity(chooser);
}
});
}
}
Based on the code in your xml file on github following changes need to be made to achieve the desired effect :
<LinearLayout
android:id="#+id/container_buttons"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:baselineAligned="false"
android:orientation="horizontal"
android:layout_below="#+id/relativeLayout">
.
.
.
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="#+id/relativeLayout">
<View
android:id="#+id/horizontal_divider1"
android:layout_width="wrap_content"
android:layout_height="2dp"
android:layout_centerInParent="true"
android:background="#color/gray"
android:layout_toLeftOf="#+id/more_info_label"
android:layout_toStartOf="#+id/more_info_label"/>
<TextView
android:id="#+id/more_info_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:padding="5dp"
android:text="#string/more_info"
android:textSize="18dp" />
<View
android:id="#+id/horizontal_divider2"
android:layout_width="wrap_content"
android:layout_height="2dp"
android:layout_centerInParent="true"
android:background="#color/gray"
android:layout_toRightOf="#+id/more_info_label"
android:layout_toEndOf="#+id/more_info_label"/>
</RelativeLayout>
The click listener in my fragment isn't working properly. I'm not getting any debug messages in my logcat whatsoever from my requestData method, nor my onClick method. I was thinking it was probably due to trying to use activity methods from the fragment, but I don't see any problems with doing that; it also wouldn't affect my onClick debug messages not showing up.
Activity:
public class MainActivity extends AppCompatActivity {
public void requestData(String first, String second) {
Log.d(“Success!”, first + “ “ + second);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
}
Fragment:
public class WelcomeFragment extends Fragment implements View.OnClickListener{
private Button mButton;
private EditText mFirstEditText;
private EditText mSecondEditText;
private View v;
public WelcomeFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_main, container, false);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mCalculateButton = (Button) v.findViewById(R.id.calculate_button);
mCalculateButton.setOnClickListener(this);
}
#Override
public void onClick(View view) {
mFirstEditText = (EditText) v.findViewById(R.id.first_editText);
String first = mFirstEditText.getText().toString();
Log.d("Button clicked", "mFirstEditText set " + first);
mSecondEditText = (EditText) v.findViewById(R.id.second_editText);
String second = mSecondEditText.getText().toString();
Log.d("Button clicked", "mSecondEditText set " + second);
v.requestData(first, second);
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<fragment
android:id="#+id/welcome_fragment"
android:name="com.example.kent.AnApplication.WelcomeFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"/>
</LinearLayout>
welcome_fragment.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivityFragment">
<TextView
android:text="#string/welcome "
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/welcome_textView"
android:textSize="20sp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="68dp"/>
<EditText
android:layout_width="280dp"
android:layout_height="wrap_content"
android:inputType="text"
android:ems="10"
android:id="#+id/first_editText"
android:layout_marginTop="60dp"
android:layout_below="#+id/welcome_textView"
android:layout_centerHorizontal="true"/>
<EditText
android:layout_width="280dp"
android:layout_height="wrap_content"
android:inputType="text"
android:ems="10"
android:id="#+id/second_editText"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/calculate_button"
android:layout_marginTop="43dp"
android:layout_below="#+id/second_editText"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
You didn't set clicked listener. Try below code:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_main, container, false);
mButton = (Button) v.findViewById(R.id.your_button_id);
mButton.setOnClickListener(this);
return v;
}
If you have some "clicked" events, you have to use if/else or switch on your onClick(); method.
Change your Fragment code to following:
public class WelcomeFragment extends Fragment implements View.OnClickListener{
private Button mButton;
private EditText mFirstEditText;
private EditText mSecondEditText;
private View v;
public WelcomeFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_main, container, false);
return v;
}
#Override
public void onViewCreated (View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mCalculateButton = (Button) view.findViewById(R.id.calculate_button);
mCalculateButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick (View v) {
mFirstEditText = (EditText) v.findViewById(R.id.first_editText);
String first = mFirstEditText.getText().toString();
Log.d("Button clicked", "mFirstEditText set " + first);
mSecondEditText = (EditText) v.findViewById(R.id.second_editText);
String second = mSecondEditText.getText().toString();
Log.d("Button clicked", "mSecondEditText set " + second);
v.requestData(first, second);
}
});
}
}
The problem is in your onclick method, you haven't find the id of that Button on which click has occurred, change your onclick() method code as:
#Override
public void onClick(View view) {
if(view.getId() == R.id.calculate_button) {
mFirstEditText = (EditText) v.findViewById(R.id.first_editText);
String first = mFirstEditText.getText().toString();
Log.d("Button clicked", "mFirstEditText set " + first);
mSecondEditText = (EditText) v.findViewById(R.id.second_editText);
String second = mSecondEditText.getText().toString();
Log.d("Button clicked", "mSecondEditText set " + second);
v.requestData(first, second);
}
}
I hope it'll work for you
I try to set the text of a TextView programmatically within a Fragment.
The code for the classes is as follows:
public abstract class AbstractFragment extends Fragment
{
#Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data)
{
this.setFileName();
}
protected abstract void setFileName();
}
public class ImplementingFragment extends AbstractFragment
{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View fragment = inflater.inflate(
R.layout.fragment_layout, container, false);
return fragment;
}
#Override
protected void setFileName()
{
String fileName = "Test.txt";
TextView textView = ((TextView) getActivity().findViewById(
R.id.text_file_name));
textView.setText(fileName);
}
}
The Layout is as follows:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin" >
<TextView
android:id="#+id/text_pdf_filename_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/text_pdf_filename"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/text_pdf_file_name"
android:layout_marginLeft="15dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
The weird thing is: within one Fragment it works, in another it does not (same parent Activity). Another fact is that after I set the text, I get it via textView.getText(). If I try to get the text in later code, I just get an empty string.
Additionally, if I debug the code, I see the text a view milliseconds, before it disappears.
Does anyone has an solution how to fix that behaviour?
Inside fragment use:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
TextView textView = ((TextView) rootView.findViewById(
R.id.text_file_name));
textView.setText(fileName);
return rootView;
}