I want to implement onclick in my fragment to change fragment.
Here is this function:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container, false);
super.onViewCreated(view, savedInstanceState);
imageView9 = (ImageView)view.findViewById(R.id.imageView3);
imageView9.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Create new fragment and transaction
Fragment newFragment = new FragEditProfile();
// consider using Java coding conventions (upper first char class names!!!)
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.content_frame_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
});
It's 'clicking' cause I hear the typical button sound. But i'm getting this error when clicks:
ssl=0xaf840c00 cert_verify_callback x509_store_ctx=0xa17d2280 arg=0x0
ssl=0xaf840c00 cert_verify_callback calling verifyCertificateChain authMethod=ECDHE_RSA
Here is my main_activity layout:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000" >
<android.support.v7.widget.Toolbar
android:id="#+id/toolbarInner"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize">
</android.support.v7.widget.Toolbar>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout android:id="#+id/content_frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#212"
android:layout_below="#+id/toolbar_app_bar_layout">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</RelativeLayout>
<android.support.design.widget.AppBarLayout
android:id="#+id/toolbar_app_bar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical" >
<include
android:layout_width="match_parent"
android:layout_height="wrap_content"
layout="#layout/top_points_bar" />
</LinearLayout>
<android.support.design.widget.TabLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/toolbar"
app:tabMode="scrollable"
app:paddingStart="16dp"
app:tabPaddingStart="16dp"
app:tabPaddingEnd="16dp"
app:tabMinWidth="96dp"
app:tabGravity="center" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
<android.support.design.widget.NavigationView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/navigation_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:background="#color/md_brown_100"
app:menu="#menu/menu_drawer"
android:textColor="#color/okurwa"
app:theme="#style/MyTabStyle"
app:headerLayout="#layout/nav_drawer_header"
app:itemTextAppearance="#style/MyTabTextStyle"
android:clipToPadding="false">
<TextView
android:id="#+id/nav_drawer_wallet_id"
android:layout_width="177dp"
android:layout_height="wrap_content"
android:textSize="15sp"
android:layout_marginTop="8dp"
android:layout_marginLeft="16dp"
android:layout_marginBottom="8dp"/>
<TextView
android:id="#+id/nav_drawer_total_credits"
android:layout_width="182dp"
android:layout_height="wrap_content"
android:textSize="16sp"
android:layout_marginTop="200dp"
android:layout_marginLeft="16dp" />
<TextView
android:id="#+id/nav_drawer_username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:textSize="22sp"
android:layout_marginTop="150dp"/>
<!--<FrameLayout-->
<!--android:layout_width="match_parent"-->
<!--android:layout_height="wrap_content"-->
<!--android:layout_gravity="bottom"-->
<!--android:background="#color/md_white_1000"-->
<!--android:elevation="4dp"-->
<!--android:layout_marginBottom="-96dp">-->
<!--<Button android:id="#+id/navigation_button_footer"-->
<!--android:layout_width="match_parent"-->
<!--android:layout_height="match_parent"-->
<!--android:text=""-->
<!--android:textSize="13sp"-->
<!--android:textColor="#color/md_grey_800"-->
<!--android:lines="3"-->
<!--android:gravity="center"-->
<!--style="#style/Widget.AppCompat.ActionButton"-->
<!--android:paddingTop="20dp"-->
<!--android:paddingLeft="20dp"-->
<!--android:paddingRight="20dp"-->
<!--android:paddingBottom="20dp"/>-->
<!--</FrameLayout>-->
</android.support.design.widget.NavigationView>
<RelativeLayout
android:id="#+id/lay_connection"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="#dimen/actmain_margintop"
android:background="#3c3c3c"
android:visibility="gone" >
<TextView
android:id="#+id/text_error"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:gravity="center"
android:text="#string/error_no_internet"
android:textColor="#color/md_white_1000"
android:textSize="#dimen/twentyfive" />
<RelativeLayout
android:id="#+id/lay_dialog"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone" >
<ProgressBar
android:id="#+id/progressBar1"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/progressBar1"
android:layout_centerHorizontal="true"
android:text="#string/error_no_internet"
android:textColor="#color/md_white_1000"
android:textSize="#dimen/twentyfive" />
</RelativeLayout>
</RelativeLayout>
</android.support.v4.widget.DrawerLayout>
Please help me guys! I see this error first time. I don't know why I'm getting this error and why it's not working. Thanks Stack's Community!
EDIT
This is full code of this fragment:
/**
* Created by otsma on 12.12.2016.
*/
import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;
import com.commonutility.PreferenceConnector;
import com.justfashion.R;
import java.util.Random;
public class OneFragment extends Fragment {
final Random rnd = new Random();
public OneFragment() {
// Required empty public constructor
}
private static TextView creditWallet;
private String[] myString;
private static final Random rgenerator = new Random();
private TextView firstName, textView13,textView14,textView15,textView16,textView17,textView18;
private Animation animShake, wbijam, load1, load2, load3, load4, load5, load6, wbijam1, wbijam2, wbijam3, wbijam4, wbijam5;
private ImageView img, imageView9,imageView19,imageView4,imageView5,imageView6,imageView7,imageView8;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public static void onUpdateView(Context aiContext) {
// TODO Auto-generated method stub
if (aiContext != null && creditWallet != null)
creditWallet.setText(PreferenceConnector.readInteger(aiContext, PreferenceConnector.WALLETPOINTS, 0) + "");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container, false);
imageView9 = (ImageView) view.findViewById(R.id.imageView3);
imageView9.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Create new fragment and transaction
Fragment newFragment = new FragEditProfile();
// consider using Java coding conventions (upper first char class names!!!)
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
});
img = (ImageView)view.findViewById(R.id.imgRandom);
imageView4 = (ImageView)view.findViewById(R.id.imageView4);
imageView5 = (ImageView)view.findViewById(R.id.imageView5);
imageView6 = (ImageView)view.findViewById(R.id.imageView6);
imageView7 = (ImageView)view.findViewById(R.id.imageView7);
imageView8 = (ImageView)view.findViewById(R.id.imageView8);
firstName = (TextView)view.findViewById(R.id.imie);
textView13 = (TextView)view.findViewById(R.id.textView13);
textView14 = (TextView)view.findViewById(R.id.textView15);
textView15 = (TextView)view.findViewById(R.id.textView16);
textView16 = (TextView)view.findViewById(R.id.textView17);
textView17 = (TextView)view.findViewById(R.id.textView18);
textView18 = (TextView)view.findViewById(R.id.textView19);
final Animation wbijam = AnimationUtils.loadAnimation(getActivity().getApplicationContext(), R.anim.wbijam);
textView13.startAnimation(wbijam);
final Animation wbijam1 = AnimationUtils.loadAnimation(getActivity().getApplicationContext(), R.anim.wbijam);
textView14.startAnimation(wbijam1);
final Animation wbijam2 = AnimationUtils.loadAnimation(getActivity().getApplicationContext(), R.anim.wbijam);
textView15.startAnimation(wbijam2);
final Animation wbijam3 = AnimationUtils.loadAnimation(getActivity().getApplicationContext(), R.anim.wbijam);
textView16.startAnimation(wbijam3);
final Animation wbijam4 = AnimationUtils.loadAnimation(getActivity().getApplicationContext(), R.anim.wbijam);
textView17.startAnimation(wbijam4);
final Animation wbijam5 = AnimationUtils.loadAnimation(getActivity().getApplicationContext(), R.anim.wbijam);
textView18.startAnimation(wbijam5);
final Animation animShake = AnimationUtils.loadAnimation(getActivity().getApplicationContext(), R.anim.shak);
img.startAnimation(animShake);
final Animation load2 = AnimationUtils.loadAnimation(getActivity().getApplicationContext(), R.anim.load2);
imageView4.startAnimation(load2);
final Animation load3 = AnimationUtils.loadAnimation(getActivity().getApplicationContext(), R.anim.load3);
imageView5.startAnimation(load3);
final Animation load4 = AnimationUtils.loadAnimation(getActivity().getApplicationContext(), R.anim.load4);
imageView6.startAnimation(load4);
final Animation load5 = AnimationUtils.loadAnimation(getActivity().getApplicationContext(), R.anim.load5);
imageView7.startAnimation(load5);
final Animation load6 = AnimationUtils.loadAnimation(getActivity().getApplicationContext(), R.anim.load6);
imageView8.startAnimation(load6);
firstName.setText("Hey,"+" " +PreferenceConnector.readString(getActivity().getApplicationContext(), PreferenceConnector.FIRST_NAME, ""));
// Inflate the layout for this fragment
final ImageView img = (ImageView) view.findViewById(R.id.imgRandom);
// return view;
// ^^^^ error remove it
Resources res = getResources();
myString = res.getStringArray(R.array.myArray);
String q = myString[rgenerator.nextInt(myString.length)];
TextView tv = (TextView) view.findViewById(R.id.tv);
tv.setText(q);
// I have 3 images named img_0 to img_2, so...
final String str = "img_" + rnd.nextInt(9);
img.setImageDrawable
(
getResources().getDrawable(getResourceID(str, "drawable",
getActivity().getApplicationContext())
));
return view;
// ^^^ move it here
}
// I have 3 images named img_0 to img_2, so...
protected final static int getResourceID
(final String resName, final String resType, final Context ctx) {
final int ResourceID =
ctx.getResources().getIdentifier(resName, resType,
ctx.getApplicationInfo().packageName);
if (ResourceID == 0) {
throw new IllegalArgumentException
(
"No resource string found with name " + resName
);
} else {
return ResourceID;
}
}
}
remove super.onViewCreated(view, savedInstanceState);
return your view
please return the view
retun view;
if the problem still persists
To Make Sure whether the problem is with Onclick or not, comment
Everything inside the onclick method and put a Toast inside it. so, i
think we could get a clear picture about the problem..
try this !!
replace the following line:
FragmentTransaction transaction = getFragmentManager().beginTransaction();
to this:
android.app.FragmentTransaction transaction = getActivity().getFragmentManager().beginTransaction();
Also don't forget to return view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container, false);
super.onViewCreated(view, savedInstanceState);
imageView9 = (ImageView)view.findViewById(R.id.imageView3);
imageView9.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Create new fragment and transaction
Fragment newFragment = new FragEditProfile();
// consider using Java coding conventions (upper first char class names!!!)
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.content_frame_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
});
return view;
}
your fragment and fragment manager should be of same type.so either import
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
OR
import android.app.Fragment;
import android.app.FragmentTransaction;
java file
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container, false);
imageView9 = (ImageView) view.findViewById(R.id.imageView3);
imageView9.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Create new fragment and transaction
Fragment newFragment = new FragEditProfile();
getActivity().getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame, newFragment)
.addToBackStack(null)
.commit();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
});
// your other contents.....
return view;
}
You better implement Interface for click event like this
public class fragment_test extends Fragment implements View.OnClickListener {
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onClick(View v) {
switch (v.getItemId()) {
case R.id.action_zoom_in:
// .....
break;
}
return true;
}
}
}
Related
Everytime I click a recycler view item on a tablet, it opens an activity rather than replacing the detail pane with a fragment.
The following line of code is what I use to detect wheter the detail pane is present:
mTwoPane = Objects.requireNonNull(getActivity()).findViewById(R.id.detail_container) != null;
Any ideas on the correct location to put this line of code?
activity 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">
<android.widget.Toolbar
android:id="#+id/masterToolbar"
android:layout_width="match_parent"
android:layout_height="?actionBarSize"
>
<LinearLayout
android:id="#+id/singleline_text_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="vertical">
<TextView
android:id="#+id/md_toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="#android:style/TextAppearance.Material.Widget.ActionBar.Title"/>
</LinearLayout>
</android.widget.Toolbar>
<RelativeLayout
android:id="#+id/master_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
sw600dp activity XML
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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">
<android.widget.Toolbar
android:id="#+id/masterToolbar"
android:layout_width="0dp"
android:layout_height="?actionBarSize"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toStartOf="#+id/detailBackgroundToolbar"
app:layout_constraintHorizontal_weight="2"
app:layout_constraintTop_toTopOf="parent">
<LinearLayout
android:id="#+id/singleline_text_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="vertical">
<TextView
android:id="#+id/md_toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="#android:style/TextAppearance.Material.Widget.ActionBar.Title"/>
</LinearLayout>
</android.widget.Toolbar>
<RelativeLayout
android:id="#+id/master_container"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintHorizontal_weight="2"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toStartOf="#+id/divider"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="#+id/masterToolbar" />
<View
android:id="#+id/divider"
android:layout_width="1dp"
android:layout_height="0dp"
android:background="?attr/dividerColor"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toEndOf="#+id/masterToolbar"
app:layout_constraintTop_toBottomOf="#+id/masterToolbar" />
<android.widget.Toolbar
android:id="#+id/detailBackgroundToolbar"
android:layout_width="0dp"
android:layout_height="?actionBarSize"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_weight="3"
app:layout_constraintStart_toEndOf="#+id/masterToolbar"
app:layout_constraintTop_toTopOf="parent" />
<android.support.v7.widget.CardView
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_margin="4dp"
app:cardCornerRadius="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/divider"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintWidth_percent="0.5">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="#layout/toolbar_dualline"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<FrameLayout
android:id="#+id/detail_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</android.support.v7.widget.CardView>
<View
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/divider"
app:layout_constraintTop_toBottomOf="#+id/detailBackgroundToolbar" />
</android.support.constraint.ConstraintLayout>
Fragment class
public class MyFragment extends Fragment {
public MyFragment() {}
List<Product> wcList;
RecyclerView mRecyclerView;
/**
* Whether or not the activity is in two-pane mode, i.e. running on a tablet device.
*/
public boolean mTwoPane;
public static MyFragment newInstance() {
return new MyFragment();
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_main, container, false);
mTwoPane = Objects.requireNonNull(getActivity()).findViewById(R.id.detail_container) != null;
mRecyclerView = view.findViewById(R.id.recyclerView_list);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
mRecyclerView.addItemDecoration(new DividerItemDecoration(Objects.requireNonNull(getContext()), LinearLayout.VERTICAL));
myList = new ArrayList<>();
String[] items = getResources().getStringArray(R.array.product_names);
String[] itemDescriptions = getResources().getStringArray(R.array.product_descriptions);
for (int n = 0; n < items.length; n++){
Product desserts = new Product();
desserts.setProductName(items[n]);
wdessertsc.setProductDescriptions(itemDescriptions[n]);
myList.add(desserts);
}
MyListAdapter listAdapter = new MyListAdapter(getActivity(), myList);
mRecyclerView.setAdapter(listAdapter);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
mTwoPane = Objects.requireNonNull(getActivity()).findViewById(R.id.detail_container) != null;
super.onActivityCreated(savedInstanceState);
}
}
Adapter class
public class MyListAdapter extends RecyclerView.Adapter<MyListAdapter.MyViewHolder> {
public boolean mTwoPane;
private Context mCtx;
private List<Product> myList;
public MyListAdapter(Context mCtx, List<Product> myList) {
this.mCtx = mCtx;
this.myList = myList;
}
#NonNull
#Override
public MyListAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mCtx);
View view = inflater.inflate(R.layout.listitem_dualline, parent,false);
return new MyListAdapter.MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final MyListAdapter.MyViewHolder holder, final int position) {
Log.d(TAG, "onBindViewHolder: called.");
final Product product = myList.get(holder.getAdapterPosition());
holder.textviewTitle.setText(product.getProductName());
holder.textviewSubtitle.setText(product.getPRoductDescription());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mTwoPane) {
Fragment newFragment;
if (product.getStationName().equals(v.getResources().getString(R.string.product_1))) {
newFragment = new FragmentProduct1();
} else {
newFragment = new FragmentProdcut2();
}
MyActivity activity = (MyActivity) v.getContext();
FragmentTransaction transaction = activity.getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.detail_container, newFragment);
transaction.commit();
} else {
Intent intent;
if (product.getStationName().equals(v.getResources().getString(R.string.product_1))) {
intent = new Intent(v.getContext(), Product1Activity.class);
} else {
intent = new Intent(v.getContext(), Product2Activity.class);
}
mCtx.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return myList.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
RelativeLayout relativeLayout;
TextView textviewTitle, textviewSubtitle;
StationViewHolder(View itemView) {
super(itemView);
mTwoPane = itemView.findViewById(R.id.detail_container) != null;
relativeLayout = itemView.findViewById(R.id.listitem_relativelayout);
textviewTitle = itemView.findViewById(R.id.listitem_title);
textviewSubtitle = itemView.findViewById(R.id.listitem_subtitle);
}
}
}
This line mTwoPane = itemView.findViewById(R.id.detail_container) != null; from your view holder will always be false.
Why?
Because, your detail_container is not part of your view holder's item container, so itemView will always return null for your view. instead pass your boolean flag from your fragment to your adapter !
I think you are checking item two pan with recyclerview item xml
mTwoPane = itemView.findViewById(R.id.detail_container) != null;
That you can check while constructing recyclerview adapter and save it from the activity content view itself.
I have a Small Fragment with three EditText and i have a Spinner with 1,2,3 as options in It.
What i want to do is that, when i select '1' from the Spinner, i want my fragment to appear below the spinner in same Activity.
And when i select '2' in Spinner, the same Fragment Should Appear Twice one below another in the same Activity and similarly for when i select '3' from Spinner.
HERE IS THE JAVA CODE
package com.globaltech2u.databaseapp1;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private Spinner spinner;
private String bookno[] = {"#","1","2","3","4"};
private ArrayAdapter<String> arrayAdapter;
private EditText editText,editText2,editText3;
private CheckBox checkBox;
private Button button;
private SQLiteDatabase db;
private Database mySQLiteOpenHelper;
private Fragment fragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText)findViewById(R.id.et1);
editText2 = (EditText)findViewById(R.id.et2);
editText3 = (EditText)findViewById(R.id.et3);
checkBox = (CheckBox)findViewById(R.id.cb1);
button = (Button)findViewById(R.id.button);
spinner = (Spinner)findViewById(R.id.booknoselectspinner);
arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, bookno);
spinner.setAdapter(arrayAdapter);
mySQLiteOpenHelper = new Database(this, "bookrecord", null, 1);
db = mySQLiteOpenHelper.getWritableDatabase();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String bookname = editText.getText().toString();
String bookno = editText2.getText().toString();
String issuedate = editText3.getText().toString();
String query = "insert into bookrecord(bookname,bookno,issuedate) values('"+bookname+"','"+bookno+"','"+issuedate+"')";
Log.e("query",query);
db.execSQL(query);
Toast.makeText(MainActivity.this, "inserted", Toast.LENGTH_SHORT).show();
}
});
final FragmentManager fragmentManager = getFragmentManager();
final FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int i, long id) {
for (int j=0;j<=i;j++){
BookentryFragment bookentryFragment = new BookentryFragment();
fragmentTransaction.replace(android.R.id.content, bookentryFragment);
}
fragmentTransaction.commit();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
HERE IS THE MAIN ACTIVITY XML FILE
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="Select No. of Books Issued"
android:id="#+id/tv4"
android:layout_centerHorizontal="true"
android:textColor="#color/colorAccent"
android:textSize="19dp"
/>
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/booknoselectspinner"
android:layout_toRightOf="#+id/tv4"
>
</Spinner>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/FM1"
android:layout_below="#+id/tv4"
android:orientation="vertical"
>
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save Record"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:id="#+id/button"
android:layout_below="#+id/FM1"
/>
</RelativeLayout>
HERE IS THE FRAGMENT FILE
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:background="#drawable/border">
<EditText
android:layout_width="300dp"
android:layout_height="wrap_content"
android:id="#+id/et1"
android:hint="Enter Book Name"
android:textAlignment="center"
android:layout_centerHorizontal="true"
android:layout_below="#+id/booknoselectspinner"
/>
<EditText
android:layout_width="300dp"
android:layout_height="wrap_content"
android:id="#+id/et2"
android:hint="Enter Book No."
android:textAlignment="center"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:layout_below="#+id/et1"
android:layout_centerHorizontal="true"
/>
<EditText
android:layout_width="300dp"
android:layout_height="wrap_content"
android:id="#+id/et3"
android:inputType="date"
android:hint="Select Issue Date"
android:textAlignment="center"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:layout_below="#+id/et2"
android:layout_centerHorizontal="true"
/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Remind me to Return"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:id="#+id/cb1"
android:layout_below="#+id/et3"
android:layout_centerHorizontal="true"
/>
</RelativeLayout>
LET ME KNOW IF I SHOULD ATTACH SOMETHING ELSE
I TRIED TO USE WHILE LOOP BUT THE APP CRASHES. PLEASE HELP
THANK YOU
I tried it with this Layout Inflater Code.
FrameLayout item = (FrameLayout) findViewById(R.id.FM1);
View child = getLayoutInflater().inflate(R.layout.fragment_bookentry, null);
item.addView(child);
It adds the Fragment once when i open the Activity.
But when i select 2 from the spinner, Nothing Happens.
I am using Switch Case for this Purpose
switch (i) {
case 0:
FrameLayout item = (FrameLayout) findViewById(R.id.FM1);
View child = getLayoutInflater().inflate(R.layout.fragment_bookentry, null);
item.addView(child);
break;
case 1:
FrameLayout item2 = (FrameLayout) findViewById(R.id.FM1);
View child2 = getLayoutInflater().inflate(R.layout.fragment_bookentry, null);
item2.addView(child2);
FrameLayout item3 = (FrameLayout) findViewById(R.id.FM1);
View child3 = getLayoutInflater().inflate(R.layout.fragment_bookentry, null);
item3.addView(child3);
break;
case 2:
FrameLayout item4 = (FrameLayout) findViewById(R.id.FM1);
View child4 = getLayoutInflater().inflate(R.layout.fragment_bookentry, null);
item4.addView(child4);
FrameLayout item5 = (FrameLayout) findViewById(R.id.FM1);
View child5 = getLayoutInflater().inflate(R.layout.fragment_bookentry, null);
item5.addView(child5);
FrameLayout item6 = (FrameLayout) findViewById(R.id.FM1);
View child6 = getLayoutInflater().inflate(R.layout.fragment_bookentry, null);
item6.addView(child6);
break;
}
Make the FrameLayout a class object, and initialize it using (FrameLayout) findViewById(R.id.FM1); only once, outside the switch statement.
In each of your case blocks, add this piece of code in the beginning:
if(item.getChildCount()>0){
item.removeAllViews();
}
EDIT: Your spinner's onItemSelected would be something like:
#Override
public void onItemSelected(AdapterView<?> parent, View view, int i, long id) {
item.removeAllViews();
for (int j=0;j<=i;j++){
View v = getLayoutInflater().inflate(R.layout.fragmentXML, null);
item.addView(v);
}
}
I started programming a few month ago and stackoverflow always was a a good dite for solving my problems. So my codes are getting better but now I´m on a point that I Need your help again.
Programm: In my App you can choose items from a spinner, then it goes to next page and so on. You have to choose from several Spinners until you get a result...
Some Code preview (Code works, but i now have to ad some more Action and I don´t know how...
package com.sio.fmf;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Button;
import android.view.ViewGroup;
import android.view.LayoutInflater;
import android.widget.TextView;
public class Koerperform extends AppCompatActivity {
String[] koerperform = {" ", "spindel- oder torpedoförmig", "langgestreckt", "hochrückig", "schlangenförmig", "welsartig", "grundelartig"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.koerperform);
Spinner mySpinner = (Spinner)findViewById(R.id.spinner);
mySpinner.setAdapter(new MyCustomAdapter(Koerperform.this,R.layout.spinner_layout, koerperform));
}
public void onClick(View v){}
public class MyCustomAdapter extends ArrayAdapter<String> {
public MyCustomAdapter(Context context, int textViewResourceId, String[] objects) {
super(context, textViewResourceId, objects);
}
private Button getSwtitchact;
{
final Button switchact = (Button) findViewById(R.id.button3);
switchact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent act = new Intent(view.getContext(), Maulstellung.class);
startActivity(act);
}
});
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
public View getCustomView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.spinner_layout, parent, false);
TextView label = (TextView) row.findViewById(R.id.koerper);
label.setText(koerperform[position]);
if (position == 0) {
label.setTextColor(0xFFF00000);
}
return row;
}
}
}
So in this state of the app you can choose the string from the spinner and then if you press Botton 3 it changes to class Maulstellung
My Problem: I want that when string "a" is choosen it goes to page xy after Button 3 is pressed and when string "b" is choosen it goes to page xyz after Button 3 is pressed,..., and so on for each string...
Hope you can help me and sorry for my bad English
I will do in this way:
Not sure is this what you need.
Declare String selectedValue and Spinner mySpinner in global(add after line String[] koerperform).
Remove Spinner beside mySpinner:
Spinner mySpinner = (Spinner)findViewById(R.id.spinner);
Inside getSwtitchact, change to this
private Button getSwtitchact;
{
final Button switchact = (Button) findViewById(R.id.button3);
switchact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectedValue=mySpinner.getSelectedItem().toString(); // here you get the selected items from spinner
if(selectedValue.equals("a"))
{
Intent act = new Intent(view.getContext(), xy.class);
startActivity(act);
}
else if(selectedValue.equals("B"))
{
Intent act = new Intent(view.getContext(), xyZ.class);
startActivity(act);
}
else
{
......
}
}
});
}
maybe this layout file helps
<pre>
<?xml version="1.0" encoding="utf-8"?>
<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=".Koerperform"
android:background="#023738">
<ImageView
android:layout_width="fill_parent"
android:layout_height="100dp"
android:id="#+id/imageView1"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:background="#drawable/header" />
<ImageView
android:layout_width="400dp"
android:layout_height="100dp"
android:id="#+id/imageView5"
android:background="#drawable/frageeins"
android:layout_below="#+id/space4"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ImageView
android:layout_width="fill_parent"
android:layout_height="120dp"
android:id="#+id/imageView6"
android:background="#drawable/fischeins"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/imageView5" />
<Spinner
android:id="#+id/spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/imageView6"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:clickable="false"
android:contextClickable="false"
/>
<Button
android:layout_width="220dp"
android:layout_height="60dp"
android:id="#+id/button3"
android:layout_marginTop="69dp"
android:background="#drawable/costum_button_weiter_gehts"
android:layout_below="#+id/imageView6"
android:layout_centerHorizontal="true" />
<Space
android:layout_width="30dp"
android:layout_height="20dp"
android:layout_below="#+id/imageView1"
android:layout_centerHorizontal="true"
android:id="#+id/space4" />
</RelativeLayout>
The project is working fine, however the problem appeared when I add "switchPage2(new limits_fragmentpageC());" this is the logcat
Here is the code for BaseFlashCardsFragment
package com.flashcards;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link Fragment} subclass.
* Use the {#link BaseFlashCardsFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class BaseFlashCardsFragment extends Fragment implements View.OnClickListener {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_POSITION = "position";
// TODO: Rename and change types of parameters
private int position;
private String mParam2;
public BaseFlashCardsFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param position Parameter 1.
* #return A new instance of fragment BaseFlashCardsFragment.
*/
// TODO: Rename and change types and number of parameters
public static BaseFlashCardsFragment newInstance(int position) {
BaseFlashCardsFragment fragment = new BaseFlashCardsFragment();
Bundle args = new Bundle();
args.putInt(ARG_POSITION, position);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
position = getArguments().getInt(ARG_POSITION, 0);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = null;
int layoutId;
switch (position) {
case 0: layoutId = R.layout.limits_flashcardsfragment1; break;
case 1:layoutId = R.layout.limits_flashcardsfragment2; break;
case 2:layoutId = R.layout.limits_flashcardsfragment3; break;
default: layoutId = R.layout.limits_flashcardsfragment4;break;
}
rootView = inflater.inflate(layoutId, container, false);
rootView.findViewById(R.id.buttonterm).setOnClickListener(this);
rootView.findViewById(R.id.buttondefinition).setOnClickListener(this);
switchPage(new limits_fragmentpageA());
switchPage1(new limits_fragmentpageB());
switchPage2(new limits_fragmentpageC());
switchPage3(new limits_fragmentpageD());
return rootView;
}
#Override
public void onClick(View view) {
int viewId = view.getId();
if (viewId == R.id.buttonterm) {
switchPage(new limits_fragmentpageA());
}
else if (viewId == R.id.buttondefinition) {
switchPage(new limits_fragmentpageAA());
}
if (viewId == R.id.buttonterm) {
switchPage1(new limits_fragmentpageB());
}
else if (viewId == R.id.buttondefinition) {
switchPage1(new limits_fragmentpageBB());
}
if (viewId == R.id.buttonterm) {
switchPage2(new limits_fragmentpageC());
}
else if (viewId == R.id.buttondefinition) {
switchPage2(new limits_fragmentpageCC());
}
if (viewId == R.id.buttonterm) {
switchPage3(new limits_fragmentpageD());
}
else if (viewId == R.id.buttondefinition) {
switchPage3(new limits_fragmentpageDD());
}
}
private void switchPage (Fragment fragment){
android.support.v4.app.FragmentManager manager = getFragmentManager();
manager.beginTransaction()
.replace(R.id.activity_main_fragmentcontainer1, fragment)
.commit();
}
private void switchPage1 (Fragment fragment){
android.support.v4.app.FragmentManager manager = getFragmentManager();
manager.beginTransaction()
.replace(R.id.activity_main_fragmentcontainer2, fragment)
.commit();
}
public void switchPage2 (Fragment fragment){
android.support.v4.app.FragmentManager manager = getFragmentManager();
manager.beginTransaction()
.replace(R.id.activity_main_fragmentcontainer3, fragment)
.commit();
}
private void switchPage3 (Fragment fragment){
android.support.v4.app.FragmentManager manager = getFragmentManager();
manager.beginTransaction()
.replace(R.id.activity_main_fragmentcontainer4, fragment)
.commit();
}
}
Here is the code for limits_fragmentpageC
package com.flashcards;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class limits_fragmentpageC extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedState) {
return inflater.inflate(R.layout.limits_fragment_flashcards_c, container, false);
}
}
Here is the XML Layout, this includes the activity_main_fragmentcontainer3
<?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"
android:orientation="vertical">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="16dp">
<include layout="#layout/include_toolbar" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:layout_marginTop="10dp"
android:text="Title 3"
android:textSize="22sp"
android:textStyle="bold" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="5dp"
android:paddingLeft="16dp"
android:paddingRight="16dp">
<Button
android:id="#+id/buttonterm"
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="Term"
android:layout_marginRight="5dp"
android:background="#drawable/button_background"
android:layout_weight="1"/>
<Button
android:id="#+id/buttondefinition"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginLeft="5dp"
android:text="Definition"
android:background="#drawable/button_background"
android:layout_weight="1"/>
</LinearLayout>
<FrameLayout
android:id="#+id/activity_main_fragmentcontainer3"
android:layout_width="match_parent"
android:layout_height="270dp"
android:layout_marginTop="16dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:background="#drawable/framelayout_border">
</FrameLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="(Swipe to Navigate) \n (3 of 10 Cards)"
android:layout_marginTop="15dp"
android:textSize="20sp"
android:layout_gravity="center"/>
</LinearLayout>
</ScrollView>
<include layout="#layout/include_toolbarbottom" />
</RelativeLayout>
Use
getActivity().getSupportFragmentManager()
in place of
getFragmentManager()
I'm pretty sure this is causing your problem because I had the same log output recently when I used getFragmentManager().
While working with support library version of Fragment, you should always use getSupportFragmentManager().
first dont use this line more than once in your layout
xmlns:android="http://schemas.android.com/apk/res/android"
second you use support fragment so you need to use getSupportFragmentManager() from the activity but because you want to use fragment inside a fragment you need to use getchildfragmentmanager()
I have a problem with a Fragment.
There is a Dialog inside a Fragment, and a Fragment inside this Dialog.
But when I add the second Fragment, there is an IllegalArgumentException : No view found for id ***** (fr.*****:id/container_list_collections) for fragment FragmentCollectionVignette.
FragmentHP.java
public class FragmentHP extends Fragment {
/** Bouton Ajouter à **/
private Button btAddTo;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, final Bundle savedInstanceState) {
View vueFragmentHP = inflater.inflate(R.layout.fragment_hp, container, false);
getFragmentManager().beginTransaction().replace(R.id.container_dernier_ajout, new FragmentDerniersAjoutsHP()).commit();
getFragmentManager().beginTransaction().replace(R.id.container_collections, new FragmentCollectionsHP()).commit();
getFragmentManager().beginTransaction().replace(R.id.container_ebooks, new FragmentEbooksHP()).commit();
getFragmentManager().beginTransaction().replace(R.id.container_games, new FragmentGamesHP()).commit();
getFragmentManager().beginTransaction().replace(R.id.container_software, new FragmentSoftwareHP()).commit();
getFragmentManager().beginTransaction().replace(R.id.container_digital_creation, new FragmentDigitalCreationHP()).commit();
btAddTo = (Button) vueFragmentHP.findViewById(R.id.bt_collections);
btAddTo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.dialog_add_to, null);
final Dialog dialog = new Dialog(getActivity());
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(view);
dialog.show();
dialog.setCanceledOnTouchOutside(false);
Button btValider = (Button) view.findViewById(R.id.bt_add_to);
getFragmentManager().beginTransaction().add(R.id.container_list_collections, new FragmentCollectionVignette()).commit();
}
});
return vueFragmentHP;
}
}
dialog_add_to.xml
<?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/tv_add_to"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/add_to"/>
<TextView
android:id="#+id/tv_choose_collection"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/choose_collection"
android:layout_below="#id/tv_add_to"/>
<FrameLayout
android:id="#+id/container_list_collections"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/tv_choose_collection"/>
<Button
android:id="#+id/bt_add_to"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/valider"
android:layout_below="#id/container_list_collections"/>
</RelativeLayout>
What is the problem ?
(Sorry for my very bad english)
i think the problem is in this line
getFragmentManager()
.beginTransaction()
.add(R.id.container_list_collections, new FragmentCollectionVignette())
.commit();
change this to
this.getActivity()
.getFragmentManager()
.beginTransaction()
.add(R.id.container_list_collections, new FragmentCollectionVignette())
.commit()