How setText in a Layout from a ViewPager - java

I try to set a Text in a Layout in a ViewPager, but if i do this there will be thrown a NullPointerException:
private ViewPager viewPager;
private ViewPagerAdapter viewPagerAdapter;
private LinearLayout dotsLayout;
private TextView[] dots;
private int[] layouts;
private Button btnNext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_slider);
viewPager = (ViewPager) findViewById(R.id.view_pager);
dotsLayout = (LinearLayout) findViewById(R.id.layoutDots);
//btnSkip = (Button) findViewById(R.id.btn_skip);
btnNext = (Button) findViewById(R.id.btn_next);
layouts = new int[]{
R.layout.slide_header_bild_text,
R.layout.slide_header_bild_text_2,
R.layout.slide_01_03,
R.layout.slide_01_04,
R.layout.slide_01_05,
R.layout.slide_01_06,
R.layout.startquiz_layout};
//These two lines are the Problem
TextView t1 = (TextView) findViewByID(R.id.header_text);
t1.setText("Test")
// adding bottom dots
addBottomDots(0);
viewPagerAdapter = new ViewPagerAdapter();
viewPager.setAdapter(viewPagerAdapter);
viewPager.addOnPageChangeListener(viewPagerPageChangeListener);
}
public void btnQuizStart(View v){
Intent intent = new Intent(this, Quiz.class);
this.startActivity(intent);
}
public void btnNextClick(View v)
{
// checking for last page
// if last page home screen will be launched
int current = getItem(1);
if (current < layouts.length) {
// move to next screen
viewPager.setCurrentItem(current);
} else {
launchHomeScreen();
}
}
ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
addBottomDots(position);
// changing the next button text 'NEXT' / 'GOT IT'
if (position == layouts.length - 1) {
// last page. make button text to GOT IT
btnNext.setText(getString(R.string.start));
} else {
// still pages are left
btnNext.setText(getString(R.string.next));
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
};
private void addBottomDots(int currentPage) {
dots = new TextView[layouts.length];
dotsLayout.removeAllViews();
for (int i = 0; i < dots.length; i++) {
dots[i] = new TextView(this);
dots[i].setText(Html.fromHtml("•"));
dots[i].setTextSize(35);
dots[i].setTextColor(getResources().getColor(R.color.inactive_dots));
dotsLayout.addView(dots[i]);
}
if (dots.length > 0)
dots[currentPage].setTextColor(getResources().getColor(R.color.active_dots));
}
private int getItem(int i) {
return viewPager.getCurrentItem() + i;
}
private void launchHomeScreen() {
startActivity(new Intent(this, MainActivity.class));
finish();
}
public class ViewPagerAdapter extends PagerAdapter {
private LayoutInflater layoutInflater;
public ViewPagerAdapter() {
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(layouts[position], container, false);
container.addView(view);
return view;
}
#Override
public int getCount() {
return layouts.length;
}
#Override
public boolean isViewFromObject(View view, Object obj) {
return view == obj;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
View view = (View) object;
container.removeView(view);
}
}
I've got the ViewPager which contains seven Pages.
I think the Layout wont be found, so the TextView is Null. I also read that I have to configure the instantiateItem method and to add there the TextView and the setter. Anybody can help?

findViewByID(R.layout.header_text)
TaxtView can't be a layout.

oh this was also a failure but not which I searched for. I had the problem with the viewpager that i didn't got the layout and so the elements of the layout was null. I fixed the instantiateItem Method so any layout will be initiated specific:
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View one = layoutInflater.inflate(R.layout.slide_type_a, container, false);
WebView header_1_a = (WebView) one.findViewById(R.id.header_slide_type_a_1);
loadHTLMContentHeader(getString(R.string.Historie1_header),header_1_a);
ImageView image_1_a = (ImageView) one.findViewById(R.id.image_slide_type_a_1);
image_1_a.setImageResource(R.drawable.picture_kap01_01);
WebView text_1_a = (WebView) one.findViewById(R.id.text_slide_type_a_1);
loadHTLMContentText(getString(R.string.Historie1), text_1_a);
View two = layoutInflater.inflate(R.layout.slide_type_a, container, false);
View three = layoutInflater.inflate(R.layout.slide_type_a, container, false);
View four = layoutInflater.inflate(R.layout.slide_type_b, container, false);
View five = layoutInflater.inflate(R.layout.slide_type_b, container, false);
View six = layoutInflater.inflate(R.layout.slide_type_b, container, false);
View seven = layoutInflater.inflate(R.layout.slide_type_b, container, false);
View eight = layoutInflater.inflate(R.layout.startquiz_layout, container, false);
View viewarr[] = {one, two, three, four, five, six, seven, eight};
container.addView(viewarr[position]);
return viewarr[position];
}
So after initiate the layout, i can get the xml element and change the content of it.

Related

Recycler View double items on change fragment

I have a problem with the recyclerview in my app i have 2 fragments in the first one there is the recycler view which has to find the songs present in the device and put them in line in the second for now nothing. when I switch from one fragment to another the recycler view items double each time.
CODE:
HomeActvity
public class HomeActivity extends AppCompatActivity {
BottomNavigationView bottomNavigationView;
RecyclerView recyclerView;
TextView noMusicTextView;
HomeFragment homeFragment = new HomeFragment();
ProvaFragment provaFragment = new ProvaFragment();
#SuppressLint("MissingInflatedId")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
getSupportActionBar().hide();
noMusicTextView = findViewById(R.id.noSongs);
recyclerView = findViewById(R.id.recycler_view);
bottomNavigationView = findViewById(R.id.barra_navigazione);
getSupportFragmentManager().beginTransaction().replace(R.id.contenitore_frammenti, homeFragment).commit();
bottomNavigationView.setOnItemSelectedListener(new NavigationBarView.OnItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.home:
getSupportFragmentManager().beginTransaction().replace(R.id.contenitore_frammenti, homeFragment).commit();
return true;
case R.id.prova:
getSupportFragmentManager().beginTransaction().replace(R.id.contenitore_frammenti, provaFragment).commit();
return true;
}
return false;
}
});
}
}
HomeFragment
public class HomeFragment extends Fragment {
ArrayList<AudioModel> songsList = new ArrayList<>();
RecyclerView recyclerView;
TextView noMusicTextView;
#SuppressLint("MissingInflatedId")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
recyclerView = view.findViewById(R.id.recycler_view);
noMusicTextView = view.findViewById(R.id.noSongs);
String[] projection = {
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.DURATION,
};
String selection = MediaStore.Audio.Media.IS_MUSIC + " !=0";
Cursor cursor = getActivity().getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,projection,selection,null,null);
while(cursor.moveToNext()){
AudioModel songData = new AudioModel(cursor.getString(1), cursor.getString(0),cursor.getString(2));
if(new File(songData.getPath()).exists())
songsList.add(songData);
}
if(songsList.size() == 0){
noMusicTextView.setVisibility(View.VISIBLE);
}else{
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(new MusicListAdapter(songsList, getContext()));
}
return view;
}
}
MusicListAdapter
public class MusicListAdapter extends RecyclerView.Adapter<MusicListAdapter.ViewHolder>{
ArrayList<AudioModel> songsList;
Context context;
public MusicListAdapter(ArrayList<AudioModel> songsList, Context context) {
this.songsList = songsList;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.recycler_item,parent,false);
return new MusicListAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
AudioModel songData = songsList.get(position);
holder.titleTextView.setText(songData.getTitle());
}
#Override
public int getItemCount() {
return songsList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView titleTextView;
ImageView iconImageView;
public ViewHolder(View itemView) {
super(itemView);
titleTextView = itemView.findViewById(R.id.music_title_text);
iconImageView = itemView.findViewById(R.id.icon_view);
}
}
}
I have tryed to use songsList.clear(); but this don't work(Sorry for my english).
When switching fragments, existing fragments aren't deleted.
Also, songsList isn't initialized; onViewCreated() is called at this time, so it seems that the transition adds the item to the songsList.
In order to solve the problem, it seems that it is necessary to do a good comparison so that the same item as the previously saved item is not added, or to not add an item every time in onViewCreated.

Opening new view inside ViewPager

Using Devlight NavigationTabBar on my android app. Here's the whole code:
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_horizontal_ntb);
initUI();
}
private void initUI() {
final ViewPager viewPager = (ViewPager) findViewById(R.id.vp_horizontal_ntb);
viewPager.setAdapter(new PagerAdapter() {
#Override
public int getCount() {
return 5;
}
#Override
public boolean isViewFromObject(final View view, final Object object) {
return view.equals(object);
}
#Override
public void destroyItem(final View container, final int position, final Object object) {
((ViewPager) container).removeView((View) object);
}
#Override
public Object instantiateItem(final ViewGroup container, final int position) {
final View viewNews = LayoutInflater.from(
getBaseContext()).inflate(R.layout.item_vp_list, null, false);
final View ViewSol = LayoutInflater.from(
getBaseContext()).inflate(R.layout.activity_sol, null, false);
final View viewProfile = LayoutInflater.from(
getBaseContext()).inflate(R.layout.activity_profile, null, false);
final View viewContact = LayoutInflater.from(
getBaseContext()).inflate(R.layout.activity_contact, null, false);
View finalView = null;
if (position == 0) {
final RecyclerView recyclerView = (RecyclerView) viewNews.findViewById(R.id.rv);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(
getBaseContext(), LinearLayoutManager.VERTICAL, false
)
);
recyclerView.setAdapter(new RecycleAdapter());
container.addView(viewNews);
finalView = viewNews;
} else if (position == 1) {
container.addView(viewSol);
finalView = viewSol;
} else if (position == 2) {
container.addView(viewProfile);
finalView = viewProfile;
} else if (position == 3){
container.addView(viewContact);
finalView = viewContact;
}
return finalView;
}
});
final String[] colors = getResources().getStringArray(R.array.default_preview);
final NavigationTabBar navigationTabBar = (NavigationTabBar) findViewById(R.id.ntb_horizontal);
final ArrayList<NavigationTabBar.Model> models = new ArrayList<>();
models.add(
new NavigationTabBar.Model.Builder(
getResources().getDrawable(R.drawable.ic_library),
Color.parseColor(colors[0]))
.selectedIcon(getResources().getDrawable(R.drawable.ic_library))
.title("News")
.badgeTitle("+10")
.build()
);
models.add(
new NavigationTabBar.Model.Builder(
getResources().getDrawable(R.drawable.ic_error_black_24dp),
Color.parseColor(colors[1]))
// .selectedIcon(getResources().getDrawable(R.drawable.ic_eighth))
.title("Solicitation")
//.badgeTitle("with")
.build()
);
models.add(
new NavigationTabBar.Model.Builder(
getResources().getDrawable(R.drawable.ic_person_black_24dp),
Color.parseColor(colors[3]))
// .selectedIcon(getResources().getDrawable(R.drawable.ic_eighth))
.title("My Account")
//.badgeTitle("icon")
.build()
);
models.add(
new NavigationTabBar.Model.Builder(
getResources().getDrawable(R.drawable.ic_phone_black_24dp),
Color.parseColor(colors[2]))
.selectedIcon(getResources().getDrawable(R.drawable.ic_phone_black_24dp))
.title("Contact")
//.badgeTitle("state")
.build()
);
navigationTabBar.setModels(models);
navigationTabBar.setViewPager(viewPager, 2);
navigationTabBar.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(final int position, final float positionOffset, final int positionOffsetPixels) {
}
#Override
public void onPageSelected(final int position) {
navigationTabBar.getModels().get(position).hideBadge();
}
#Override
public void onPageScrollStateChanged(final int state) {
}
});
navigationTabBar.postDelayed(new Runnable() {
#Override
public void run() {
for (int i = 0; i < navigationTabBar.getModels().size(); i++) {
final NavigationTabBar.Model model = navigationTabBar.getModels().get(i);
navigationTabBar.postDelayed(new Runnable() {
#Override
public void run() {
//model.showBadge();
}
}, i * 100);
}
}
}, 500);
}
As you can see, whenever I choose a tab it opens the view inside the view pager.
However, I have no idea how to open another view when I click on a button. I tried to start a whole new activity with intent but it crashes and it's not really what I want.
What I want is to open the view on the viewpager ViewPager viewPager = (ViewPager) findViewById(R.id.vp_horizontal_ntb);
If I implement this:
public void openNewView(View view) {
//the code to open a view inside the viewpager should go here
}
How can I proceed?
Add a view to your viewPager in the layout that is originally set to Visibility = GONE or Invisible and change it to Visible when you want it to be visible on screen.
https://developer.android.com/reference/android/view/View.html#GONE
Or use a layoutInflater to add a view from another layout to your viewpager
https://developer.android.com/reference/android/view/LayoutInflater.html
To open a new view on click of some button you can do this:
Suppose that you want to have a new view on the first button, then in the method instantiateItem of PagerAdapter you can check if position is 0 or not.
If the position if 0, then you can inflate that layout which you want to display.
something like this:
#Override
public Object instantiateItem(final ViewGroup container, final int position) {
if (position == 0)
{
final View view = LayoutInflater.from(
getBaseContext()).inflate(R.layout.your_layout, null, false);
final TextView txtPage = (TextView) view.findViewById(R.id.txt_vp_item_page);
txtPage.setText(String.format("Page #%d", position));
container.addView(view);
return view;
}
else if (position == 1)
{
final View view = LayoutInflater.from(
getBaseContext()).inflate(R.layout.item_vp, null, false);
final TextView txtPage = (TextView) view.findViewById(R.id.txt_vp_item_page);
txtPage.setText(String.format("Page #%d", position));
container.addView(view);
return view;
}
else
{
final View view = LayoutInflater.from(
getBaseContext()).inflate(R.layout.item_vp, null, false);
final TextView txtPage = (TextView) view.findViewById(R.id.txt_vp_item_page);
txtPage.setText(String.format("Page #%d", position));
container.addView(view);
return view;
}
}
To make your code more modular you can use make your custom fragments and and them in your adapter.
Hope this helps

I have created RecyclerView and when the screen orientation change then duplicate items are added to the top

I have initialize RecyclerView in fragment as follows.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.fragment_home_page, container, false);
initialiseView(view);
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(new HomepageRecyclerViewAdapter(getActivity()));
return view;
}
private void initialiseView(View view){
recyclerView=(RecyclerView)view.findViewById(R.id.recyclerView);
}
Then I have created a RecyclerView adapter as follows.
public class HomepageRecyclerViewAdapter extends RecyclerView.Adapter<HomepageRecyclerViewAdapter.ViewHolders> {
private Context context;
public HomepageRecyclerViewAdapter(Context context) {
this.context = context;
}
#Override
public HomepageRecyclerViewAdapter.ViewHolders onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.
from(parent.getContext()).
inflate(R.layout.homepage_recycler_view_content, parent, false);
return new ViewHolders(itemView);
}
#Override
public void onBindViewHolder(final HomepageRecyclerViewAdapter.ViewHolders holder, int position) {
prepareHorizontalScrollView(holder.videoOuterParent);
}
#Override
public int getItemCount() {
return 50;
}
static class ViewHolders extends RecyclerView.ViewHolder {
protected LinearLayout parentContent;
protected ImageView videoImage;
protected RelativeLayout videoInnerParent;
protected HorizontalScrollView horizontalScrollView;
protected LinearLayout videoOuterParent;
public ViewHolders(View view) {
super(view);
parentContent = (LinearLayout) view.findViewById(R.id.parent_content);
videoImage = (ImageView) view.findViewById(R.id.video_image);
videoInnerParent = (RelativeLayout) view.findViewById(R.id.video_inner_parent);
videoOuterParent = (LinearLayout) view.findViewById(R.id.video_outer_parent);
horizontalScrollView = (HorizontalScrollView) view.findViewById(R.id.horizontal_scroll_view);
videoInnerParent.getViewTreeObserver()
.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
}
});
}
}
private void prepareHorizontalScrollView(LinearLayout videoOuterParent) {
videoOuterParent.removeAllViews();
for (int i = 0; i < 10; i++) {
RelativeLayout relativeLayout = new RelativeLayout(context);
relativeLayout.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
final ImageView imageView = new ImageView(context);
imageView.setAdjustViewBounds(true);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setImageResource(R.drawable.gire_khursani);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
layoutParams.setMargins(10, 10,0, 10);
imageView.setLayoutParams(layoutParams);
relativeLayout.addView(imageView);
videoOuterParent.addView(relativeLayout);
}
}
}
Now the problem i have faced is when i take screen to portrait mode to landscape mode the items is being duplicate at top.I cannot figure out the cause.
Here is the link of the screen shot
https://drive.google.com/file/d/0B2oBJsY3oyCtUTZsS1RmdC1RclU/view?usp=sharing
yes i added the line given by #itsa04g9 and now it works fine.
android:configChanges="orientation|screenSize"
It seems you don't have any List values, just static values to display. Put you RecyclerView code in onConfigurationChanged() from where you have initialized.
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Your RecyclerView logic
}

Can't swiping between fragments in viewpager with buttons

I would change fragment in the viewpager using a button in every fragment. So in the fragment in position 0 i have a button and onClick i'll change in second fragment (position 1) and so on. Actually i'm using this code in the fragment at position 0:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.open_welcome_fragment_layout, container,
false);
final WelcomeViewPager pagerV = new WelcomeViewPager();
Button nextBtnOpen = (Button)view.findViewById(R.id.button_next_open);
nextBtnOpen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
((WelcomeViewPager)getActivity()).setCurrentItem(1, true);
}
});
return view;
}
position 1:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.firstwelcomefrg, container, false);
final WelcomeViewPager pagerV = new WelcomeViewPager();
Button nextBtn = (Button)view.findViewById(R.id.button_next_one);
nextBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
((WelcomeViewPager)getActivity()).setCurrentItem(2, true);
}
});
return view;
}
position 2:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.secondwelcomefrg, container,
false);
final WelcomeViewPager pagerV = new WelcomeViewPager();
Button nextBtnTwo = (Button)view.findViewById(R.id.button_next_two);
nextBtnTwo.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
((WelcomeViewPager)getActivity()).setCurrentItem(3, true);
}
});
return view;
}
and in my ViewPager Activity i created this method:
public void setCurrentItem (int item, boolean smoothScroll) {
mViewPager.setCurrentItem(item, smoothScroll);
}
unfortunatelly not works. I can change from first to second fragment but every fragment returns to second.. Seems that the only one position accepted is the first one. In this case:
((WelcomeViewPager)getActivity()).setCurrentItem(1, true);
why this behaviour?
I think what you are trying to do is to have tabs and each tab to help switch between views. You should use actionBar tabs for this, not buttons.
This should help. It is a pretty detailed tutorial.
Do you want Button ? I use for similary problem solving with listener. Example of code below. Maybe help.
PagerActivity.java
import com.example.zzztest2.MyPagerAdapter.OnPagerItemSelected;
public class PagerActivity extends Activity implements OnPagerItemSelected {
ViewPager viewPager;
ArrayList<Bitmap> bitmapArray=null;
ArrayList<String> textArray=null;
ArrayList<String> urlArray=null;
int pagexi;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reklamapager);
viewPager = (ViewPager) findViewById(R.id.view_pager);
//setting adapter
new readAsync().execute();
}//end oncreate
//switch page
public void pagerItemSelected(int newposition) {
viewPager.setCurrentItem(newposition);
}
Setting my adapter in onpostexecute Async
protected void onPostExecute(String file_url) {
MyPagerAdapter adapter = new MyPagerAdapter(PagerActivity.this, textArray, urlArray, bitmapArray, PagerActivity.this );
viewPager.setAdapter(adapter);
//start position
int pagexi = 2;
viewPager.setCurrentItem(pagexi);
}
MyPagerAdapte.java
public class MyPagerAdapter extends PagerAdapter {
Context context;
OnPagerItemSelected mListener;
ArrayList<String> textArray;
ArrayList<String> urlArray;
ArrayList<Bitmap> bitmapArray;
ImageView imageView;
TextView textreklama1;
Button btnSwitchPage;
public Activity activity;
String firmax;
String adresarx;
MyPagerAdapter(Context context, ArrayList<String> textArray, ArrayList<String> urlArray, ArrayList<Bitmap> bitmapArray, OnPagerItemSelected listener){
this.context=context;
this.textArray=textArray;
this.urlArray=urlArray;
this.bitmapArray=bitmapArray;
this.mListener = listener;
}
#Override
public int getCount() {
return textArray.size();
}
public Object instantiateItem(ViewGroup collection, int position) {
LayoutInflater inflater = (LayoutInflater) collection.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.reklamator_new, null);
String indexx = textArray.get(position).toString();
String delims2 = "[;]+";
String[] riadokxxx = indexx.split(delims2);
String ucex = riadokxxx[0].trim();
String dokx = riadokxxx[1].trim();
EditText inputUce = (EditText) view.findViewById(R.id.inputUce);
inputUce.setText(ucex);
EditText inputDok = (EditText) view.findViewById(R.id.inputDok);
inputDok.setText(dokx);
btnSwitchPage = (Button) view.findViewById(R.id.btnSwitchPage);
btnSwitchPage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//here set new position
int xxx=1;
mListener.pagerItemSelected(xxx);
}
});
((ViewGroup) collection).addView(view, 0);
return view;
}
#Override
public void destroyItem(ViewGroup arg0, int arg1, Object arg2) {
((ViewGroup) arg0).removeView((View) arg2);
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
//new position
public interface OnPagerItemSelected {
void pagerItemSelected(int xxx);
}
}

Add Item to ListView

I'm trying to add items at runtime to ListView placed on Tab.
But when I do so, I get an error. There are 3 tabs and I'm not using ListFragments, because I have different content in all tabs
my code below
SwipeTabFragment.java
public class SwipeTabFragment extends Fragment {
private String tab;
private int color;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getArguments();
tab = bundle.getString("tab");
color = bundle.getInt("color");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.bookshelf, null);
TextView tv = (TextView) view.findViewById(R.id.textView);
tv.setText(tab);
view.setBackgroundResource(color);
return view;
}
}
TabPagerAdapter.java
public class TabPagerAdapter extends FragmentPagerAdapter {
public TabPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
Bundle bundle = new Bundle();
String tab = "";
int colorResId = 0;
SwipeTabFragment swipeTabFragment = new SwipeTabFragment();
switch (index) {
case 0:
tab = "BookShelf";
bundle.putString("tab",tab);
swipeTabFragment.setArguments(bundle);
return swipeTabFragment;
// break;
case 1:
tab = "Now Listening";
colorResId = R.color.color2;
BookFragment bookFragment = new BookFragment();
return bookFragment;
//break;
case 2:
tab = "Library";
colorResId = R.color.color3;
TabLibrary tabLibrary = new TabLibrary();
return tabLibrary;
break;
}
return null;
}
#Override
public int getCount() {
return 3;
}
}
TabLibrary.java
public class TabLibrary extends Fragment {
final String LOG_TAG = "myLogs";
ListView lvLibList;
ImageButton btAddItem;
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.library, parent, false);
ListView lvLibList = (ListView)v.findViewById(R.id.lvLibList);
ImageButton btn = (ImageButton)v.findViewById(R.id.btAddItem);
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, list);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText edit = (EditText)v.findViewById(R.id.eAddItem);
list.add(edit.getText().toString());
edit.setText("");
adapter.notifyDataSetChanged();
}
};
btn.setOnClickListener(listener);
lvLibList.setAdapter(adapter);
return v;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
#Gurusharan S is right, the problem is about the names of your variables. To avoid confusions I'd suggest to change your code to this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.library, parent, false); //Change the name from v to view
ListView lvLibList = (ListView)view.findViewById(R.id.lvLibList);
ImageButton btn = (ImageButton)view.findViewById(R.id.btAddItem);
EditText edit = (EditText)view.findViewById(R.id.eAddItem); //Initialize the EditText outside of the click method
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, list);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
list.add(edit.getText().toString());
edit.setText("");
adapter.notifyDataSetChanged();
}
};
btn.setOnClickListener(listener);
lvLibList.setAdapter(adapter);
return view;
}
And in the future I'd advice to give your variables more meaningful names, sometimes it takes you a little more coding but it is worth it.
Posting my comment as answer, as I'm pretty sure that is the issue:
The variable edit seems to be null. That is because when you call v.findViewById, you are actually calling it on the view that was clicked and NOT the fragment's view.
So you got two options:
Change the name of the fragment's view. eg. View v1 = inflater.inflate(R.layout.library, parent, false); and then change the line to v1.findViewById
Change the name of the argument of onClick. eg. public void onClick(View v1) {.
Hope that helps.

Categories