Hi here you can see my code.
My probleme is : with this code my EditText and my Button field are null so i can't do anithing with them.
Plz can you help me to access to this button.
For the activity it's autogenerated by eclipse.
public class MainActivity extends ActionBarActivity {
private EditText commentaire;
private Button addReleve;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
this.commentaire = (EditText) findViewById(R.id.commentaire);
this.addReleve = (Button) findViewById(R.id.addReleve);
addReleve.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
Toast toast = Toast.makeText(getApplicationContext(), "LOL", Toast.LENGTH_LONG);
toast.show();
return false;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
public void resetInterface(){
this.commentaire.setText("");
this.addReleve.setEnabled(true);
}
}
XML Layout (fragment_main.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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.relevegps.MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="32dp"
android:text="Relevé GPS"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/addReleve"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="92dp"
android:text="Ajouter le relevé" />
<EditText
android:id="#+id/commentaire"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:ems="10" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/commentaire"
android:layout_centerHorizontal="true"
android:layout_marginBottom="26dp"
android:text="Commentaire" />
</RelativeLayout>
try this also.
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
EditText commentaire = (EditText) rootView.findViewById(R.id.commentaire);
Button addReleve = (Button) rootView.findViewById(R.id.addReleve);
commentaire.setText("");
addReleve.setEnabled(true);
return rootView;
}
// Also this goes in this class
public void resetInterface(){
this.commentaire.setText("");
this.addReleve.setEnabled(true);
}
}
Your problem is that those two views are in your Framgent's xml and you can only find those in that fragment. So just move the commentaire and addReleve specific stuff to your fragment class.
public static class PlaceholderFragment extends Fragment {
// Variables moved from MainActivity to here
private EditText commentaire;
private Button addReleve;
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
// To get views in fragment you need the base view (=rootView)
// Example
this.commentaire = (EditText) rootView.findViewById(R.id.commentaire);
// Put the code in here !
// ...
return rootView;
}
// Also this goes in this class
public void resetInterface(){
this.commentaire.setText("");
this.addReleve.setEnabled(true);
}
}
Related
I'm new to Android development. I just created navigation drawer with fragment of my own (simple calculator app). In that fragment I have added a click method for the buttons. But that is not working.
Note: I have defined the onclick method in xml view
calculator fragment:
public class SimpleCalcActivity extends Fragment {
private TextView mDisplay;
private boolean mDisplayIsEmpty = true;
private boolean mFirstNumberReceived;
private boolean mNumberEntered;
private boolean mPointEntered;
private double sNum1;
private double sNum2;
private static OperationsAndFunctions.OperEnum sOperation;
private static OperationsAndFunctions.FuncEnum sFunction;
private Animation anim;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_simplecalc,null);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mDisplay = (TextView) view.findViewById(R.id.resultview);
mDisplay.setText("0");
}
public void num_Clicked(View view) {
Button button = (Button) view;
int number = 0;
switch (button.getId()) {
case R.id.n_one:
number = 1;
anim = AnimationUtils.loadAnimation(getContext(),
R.anim.btn_anim);
button.startAnimation(anim);
break;
case R.id.n_two:
number = 2;
anim = AnimationUtils.loadAnimation(getContext(),
R.anim.btn_anim);
button.startAnimation(anim);
break;
...
}
...
}
calculator view:
<Button
android:id="#+id/o_root"
android:layout_width="70dp"
android:layout_height="wrap_content"
android:background="#drawable/button"
android:text="#string/root"
android:onClick="func_Clicked"
android:textStyle="bold"
android:textSize="30sp"
android:layout_marginRight="5dp"
android:layout_marginLeft="5dp"
android:textColor="#android:color/white"/>
<Button
android:tag="nums"
android:id="#+id/n_seven"
android:layout_width="70dp"
android:layout_height="wrap_content"
android:background="#drawable/button"
android:text="#string/_7"
android:onClick="num_Clicked"
android:textStyle="bold"
android:textSize="30sp"
android:layout_marginRight="5dp"
android:layout_marginLeft="5dp"
android:textColor="#android:color/white"/>
Navigation drawer:
...
public boolean onNavigationItemSelected(MenuItem item) {
Fragment fragment = null;
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_simple_calc) {
fragment = new SimpleCalcActivity();
}
}
if (fragment != null){
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.screen_area, fragment);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout)
findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
...
I have tried setOnClickListener Method, it does not worked for me
I'm looking for your help. Thanks in advance.
Your fragment code is wrong. Try this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_my_dialog, container, false);
cancelAction = view.findViewById(R.id.cancelActionId);
cancelAction.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do anything.
}
});
return view;
}
Your aren't Return the view.
Try to write code with this structure, your problem will be gone.
You should define num_Clicked() method in Your Activity not Fragment.
Move the method to the activity in which you are using that fragment
I have an activity in which i desire to retrieve data (the text in some edit texts) when i click a button in my toolbar :
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
break;
case R.id.mnufragmentOk:
RETRIEVE EDITTEXT!!
break;
}
this is my activity :
public class ViatgeDetallTransportActivity extends AppCompatActivity{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_transportation);
Toolbar myToolbar = (Toolbar) findViewById(R.id.tlbMenuTransportation);
setSupportActionBar(myToolbar);
getSupportActionBar().setTitle("TravelApp ACtFra");
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ViatgeDetallTransportFragment fragment = new ViatgeDetallTransportFragment();
getSupportFragmentManager().beginTransaction()
.add(R.id.activity_fragment_transportation,fragment)
.commit();
}
}
And my fragment class :
public class ViatgeDetallTransportFragment extends Fragment {
public static final String ARG_ID = "id";
public ViatgeDetallTransportFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_transportation, container, false);
return rootView;
}
}
With a simple layout :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="#+id/layout_fragment_transportation" xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Transportation"
/>
<EditText
android:layout_width="100dp"
android:layout_height="wrap_content"
android:id="#+id/edtTitleFragmentTransportation"/>
<EditText
android:layout_width="100dp"
android:layout_height="wrap_content"
android:id="#+id/edtDescripcioFragmentTransportation"/>
<EditText
android:layout_width="100dp"
android:layout_height="wrap_content"
android:id="#+id/edtTypeFragmentTransportation"/>
</LinearLayout>
In the activity, when I click the toolbar button "mnufragmentOk" i want to recieve the data in the edit texts, so i can create a custom object.
Keep the fragment instance as a global variable in Activity
public class ViatgeDetallTransportActivity extends AppCompatActivity{
ViatgeDetallTransportFragment fragment;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_transportation);
Toolbar myToolbar = (Toolbar) findViewById(R.id.tlbMenuTransportation);
setSupportActionBar(myToolbar);
getSupportActionBar().setTitle("TravelApp ACtFra");
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
fragment = new ViatgeDetallTransportFragment();
getSupportFragmentManager().beginTransaction()
.add(R.id.activity_fragment_transportation,fragment)
.commit();
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
break;
case R.id.mnufragmentOk:
String s=fragment.getFirstEditTextData();
break;
}
}
Impliment the getFirstEditTextData() method inside of your Fragment
You can set a TAG for your fragment:
ViatgeDetallTransportFragment fragment = new ViatgeDetallTransportFragment();
getSupportFragmentManager().beginTransaction()
.add(R.id.activity_fragment_transportation,fragment, "MyFragment").commit();
Then you can find that instance when you click the button:
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
break;
case R.id.mnufragmentOk:
ViatgeDetallTransportFragment fragment = getSupportFragmentManager.findFragmentByTag("MyFragment");
break;
}
Finally, you can find the TextView and get it's value:
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
break;
case R.id.mnufragmentOk:
ViatgeDetallTransportFragment fragment = getSupportFragmentManager.findFragmentByTag("MyFragment");
EditText editText = (EditText)fragment.getView().findViewById(R.id.my_text_view);
String string = editText.getText().toString().trim();
break;
}
plus:
don't forget to set an ID to your EditTexts:
<EditText
android:id="#+id/my_edit_text"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:id="#+id/edtTypeFragmentTransportation"/>
and you need to reference them in your fragment's view creation:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_transportation, container, false);
EditText editText = (EditText)rootView.findViewById(R.id.my_edit_text);
return rootView;
}
I have an activity file which uses a ViewPager to show different pages - each which are fragments with a video. I want some of the pages to have buttons which when I press turn into a pop up to display some information - is this possible?
I've tried this code below:
Here is the code in my fragment java:
public class MassageandBeauty extends Fragment implements View.OnClickListener {
Button btnPopup;
showPopup showPopup;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.first_fragment, container, false);
btnPopup = (Button)v.findViewById(R.id.cavern);
btnPopup.setOnClickListener(this);
return v;
}
//#Override
public void onViewCreated(View v) {
btnPopup = (Button)v.findViewById(R.id.cavern);
btnPopup.setOnClickListener(this);
}
//#Override
#Override
public void onClick(View parent) {
new showPopup(getActivity().getApplicationContext()).cavern(parent);
}
Here is the code in my popup:
public class showPopup extends ActionBarActivity {
Context ctx;
public showPopup(Context ctx){
this.ctx = ctx;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_popup_layout);
Typeface myTypeface = Typeface.createFromAsset(getAssets(), "fonts/Raleway-Black.ttf");
TextView myTextView = (TextView)findViewById(R.id.textViewtop);
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
myTextView.setTypeface(myTypeface);
}
public void cavern(View parent) {
final PopupWindow popup = new PopupWindow(ctx);
ViewGroup.LayoutParams para = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
TextView tvMessage = new TextView(ctx);
Button btnDismiss = new Button(ctx);
tvMessage.setLayoutParams(para);
btnDismiss.findViewById(R.id.close);
btnDismiss.setLayoutParams(para);
btnDismiss.setWidth(20);
btnDismiss.setHeight(10);
btnDismiss.setText("x");
popup.setContentView(btnDismiss);
popup.setWidth(1200);
popup.setHeight(800);
popup.showAtLocation(parent, Gravity.CENTER_HORIZONTAL, 10, 10);
popup.update();
btnDismiss.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
popup.dismiss();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_popup_layout, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(new CalligraphyContextWrapper(newBase));
}
}
Here is the xml of my PopUp
LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:id="#+id/showpopup"
android:layout_height="fill_parent"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:background="#8000"
android:orientation="vertical"
tools:context="morzineappy.morzineappy.showPopup">
<TextView
android:id="#+id/textViewtop"
android:layout_marginTop="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:textColor="#FFF"
android:textSize="30sp"
android:text="The Cavern" />
<Button
android:id="#+id/close"
android:layout_marginBottom="10dp"
android:layout_marginRight="10dp"
android:layout_marginLeft="1200dp"
android:layout_gravity="left"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="x" />
<ImageView
android:id="#+id/poster"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/cavern"
android:layout_marginTop="20dp"
android:layout_marginLeft="800dp"
android:layout_marginRight="20dp"
android:layout_gravity="right" />
<TextView
android:id="#+id/textViewtop"
android:layout_width="800dp"
android:layout_height="wrap_content"
android:layout_marginRight="20dp"
android:layout_marginTop="60dp"
android:layout_marginLeft="20dp"
style="#style/BusinessFont"
android:text="Text"
/>
For some reason it won't display the text in the popup- I want to add the layout into the popup but I'm not sure how- any ideas?!
First create your popup or message dialog with extending DialogFragment, then on button click:
MyDialogFragment dialog = new MyDialogFragment(....);
dialog.show(getActivity().getSupportFragmentManager(), "name of fragment here");
Your question is not very clear, but I'll assume that you're trying to use something like an AlertDialog. Typically when creating these, you need a Context object as an argument. In an Activity, you can usually create an AlertDialog like so:
AlertDialog d = new AlertDialog(this);
But I'm guessing that your issue is that since you are in a fragment, the this object is not a Context. So for you, it would be more like so:
AlertDialog d = new AlertDialog(getActivity());
I'm new on Android and I'm trying to do my first app.
I've read a lot of posts here about the same problem I got, but couldn't figure it out.
I hope you can help me.
My app has several Activities. In this case in particular, I'm sending a string which I want to put in a textview. When I tried to do this, the app crashed. So, I read a lot of posts and "catched" the null pointer. But that meant my setContentView is not working.
I'm working with ADT downloaded on 2014-06-21.
Tried to clean Eclipse, but it remains the same.
Tried to change the name of tvGrupo (before, it was textView1).
Also, I'm not very good at english, as you can tell and more important, since I'm new in Android I'm not use to all the words used commonly to describe process... :(
So, please be very specific.
Thanks for all the help!
This is my code:
public class DisplayGrup extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_grup);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
TextView tvgrupo = (TextView) findViewById(R.id.tvGrupo);
if (tvgrupo == null) {
// this is how i know i received a null pointer.
Toast.makeText(getApplicationContext(), "Puntero nulo", Toast.LENGTH_SHORT).show();
} else {
tvgrupo.setText("hola");
Toast.makeText(getApplicationContext(), "Obteniendo dato:" + tvgrupo.toString(), Toast.LENGTH_SHORT).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.display_grup, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_display_grup,
container, false);
return rootView;
}
}
public void clickBorrar(View view) {
// This works just fine.
TextView tv = (TextView) findViewById(R.id.tvGrupo);
tv.setText("hhhh");
}
}
This is my 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:gravity="top"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.mula_saltadora.DisplayGrup$PlaceholderFragment" >
<Button
android:id="#+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:onClick="clickBorrar"
android:text="Borrar" />
<TextView
android:id="#+id/tvGrupo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/button1"
android:layout_alignParentTop="true"
android:layout_marginTop="10dp"
android:layout_toLeftOf="#+id/button1"
android:text="Grupo"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="#+id/button2"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/editText1"
android:layout_alignParentRight="true"
android:text="Agregar" />
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/tvGrupo"
android:layout_below="#+id/tvGrupo"
android:layout_above="#+id/editText1"
>
</ListView>
</RelativeLayout>
Your textview is in fragment layout so put your code in onCreateView instead in onCreate:
View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_display_grup,
container, false);
TextView tvgrupo = (TextView) rootView.findViewById(R.id.tvGrupo);
if (tvgrupo == null) {
// this is how i know i received a null pointer.
Toast.makeText(getActivity(), "Puntero nulo",
Toast.LENGTH_SHORT).show();
} else {
tvgrupo.setText("hola");
Toast.makeText(getActivity(), "Obteniendo dato:" +
tvgrupo.toString(), Toast.LENGTH_SHORT).show();
}
return rootView;
}
public void clickBorrar(View view) {
// This works just fine.
TextView tv = (TextView) rootView.findViewById(R.id.tvGrupo);
tv.setText("hhhh");
}
Edit:
Change getApplicationContext() to getActivity() and make rootView global variable in fragment and use it in function clickBorrar too. See edited code.
Make your rootView accessible to all your fragment, and use it to call findViewById. Its something like this:
public static class PlaceholderFragment extends Fragment {
View rootView;
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_display_grup,
container, false);
return rootView;
}
}
public void clickBorrar(View view) {
// This works just fine.
TextView tv = (TextView) rootView.findViewById(R.id.tvGrupo);
tv.setText("hhhh");
}
}
In your case, In your activity cannot have textview, so you cannot call findViewById. so you must call rootView caused Fragment.
e.g :
in activity findViewByID.......
in fragment rootView......
or outside rootView if you using fragment you can using getView().
I am following a fragment example https://gist.github.com/daichan4649/2947119.
I am adding the fragment dynamically after button click event.But the fragment is overlapping with the button. And when I am pressing back key on this screen, activity is closed.
Need help to display only the fragment after button is clicked and if the back is pressed after adding fragment, then only the top fragment should be closed.
Here are my test code.
MainActivity.java
public class MainActivity extends FragmentActivity {
private static Button mBtn;
private static final String TAG_LIST = "list";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState != null) {
return;
}
mBtn = (Button) findViewById(R.id.clickme);
mBtn.setOnClickListener(new View.OnClickListener() {
#SuppressLint("NewApi")
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Fragment fragment = getFragmentManager().findFragmentByTag(TAG_LIST);
if (fragment == null) {
fragment = TestListFragment.newInstance();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(android.R.id.content, fragment, TAG_LIST);
ft.commit();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
TestListFragment.java
public class TestListFragment extends ListFragment {
public static TestListFragment newInstance() {
return new TestListFragment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
ViewGroup rootView = (ViewGroup) inflater.inflate(android.R.id.content, container, false);
return rootView;
}
#SuppressLint("NewApi")
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), R.layout.list_column, R.id.text);
setListAdapter(adapter);
adapter.addAll(createDataList(10));
}
private static List<String> createDataList(int counts) {
List<String> list = new ArrayList<String>();
for (int i = 0; i < counts; i++) {
list.add("i=" + i);
}
return list;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
//Toast.makeText(getActivity(), "List Item Clicked", Toast.LENGTH_SHORT).show();
//On item click, launch the DialogFragment
TestDialogFragment moveFragment = new TestDialogFragment( );
moveFragment.show(getFragmentManager(), "Test List Fragment");
}
TestDilogFragment.java
public class TestDialogFragment extends DialogFragment {
private View testDialogFragment = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//Fill the layout as per Your requirement
testDialogFragment = inflater.inflate(R.layout.activity_list_fragment, container);
return testDialogFragment;
}
}
activity-main.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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/clickme"
android:text="ClickMe" />
</RelativeLayout>
activity_list_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: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:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
</RelativeLayout>
Change your activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parentt" >
<Button
android:id="#+id/clickme"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Button" />
<FrameLayout
android:id="#+id/container"
android:layout_above="#id/clickme"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
>
</FrameLayout>
</RelativeLayout>
You have a Button at the bottom and a ViewGroup which is a FrameLayout at the top. You add the Fragment to the container.
And in ManiActivtiy change to
ft.add(R.id.container, fragment, TAG_LIST);