Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
My task is to convert an activity to a fragment.
I did some changes but it still doesn't work. I am missing something, but I can't figure it out. One problem I do see is that the public class QuoteFragment extends SingleFregmentActivity is underline...not sure what I forget to do. Help please!
When I wan converting the activity to a fragment what did I forget?
Code for the activity...
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.content.Intent;
/**
* Main activity for the application.
* Displays a series of quotes
*/
public class QuoteFragment extends SingleFragmentActivity{
/** Key for fact about author stored in Intent sent to AuthorFactActivity. */
public static final String EXTRA_AUTHOR_FACT =
"edu.andrews.cptr252.stephanien.quoteoftheday.author_fact";
private static final String KEY_QUOTE_INDEX = "quoteIndex";
/**ImageView used to display inspirational image*/
private ImageView mImageView;
private TextView mQuoteTextView;
private TextView mAuthorTextView;
private Button mNextButton;
/**Quotes used in app */
private Quote[] mQuoteList = new Quote[]{
new Quote(R.string.quote_text_0, R.string.quote_author_0,
R.string.author_fact_0, R.drawable.mountain_pic),
new Quote(R.string.quote_text_1, R.string.quote_author_1,
R.string.author_fact_1, R.drawable.lier),
new Quote(R.string.quote_text_2, R.string.quote_author_2,
R.string.author_fact_2, R.drawable.math),
new Quote(R.string.quote_text_3, R.string.quote_author_3,
R.string.author_fact_3, R.drawable.smiley),
new Quote(R.string.quote_text_4, R.string.quote_author_4,
R.string.author_fact_4, R.drawable.th),
};
/** Index of current quote in list */
private int mCurrentIndex = 0;
/** Launch activity to display author fact */
private void displayAuthorFact(){
//Create intent with name of class for second activity.
//This intent will be sent to the Activity Manager in the OS
//Which will launch the activity.
Intent i = new Intent(QuoteFragment.this, AuthorFactActivity.class);
//Add extra containing resource id for fact
i.putExtra(EXTRA_AUTHOR_FACT, mQuoteList[mCurrentIndex].getAuthorFact());
//Send the intent to the activity manager.
startActivity(i);
}
/**
* Remember the current quote when the activity is destroyed
* #param savedInstanceState Bundle used for saving identity of current quote
*/
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
//Stored the index of the current quote in the bundle.
//Use our key to access the value later.
savedInstanceState.putInt(KEY_QUOTE_INDEX, mCurrentIndex);
}
/**
* Setup and inflate layout.
* #param savedInstanceState Previously saved Bundle
*/
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View v = inflater.inflate(R.layout.activity_fragment, container, false);
//mQuoteTextView.setText("This should generate an error. Do you see why?");
//Re-display the same quote we were on when activity destroyed
if(savedInstanceState != null){
mCurrentIndex = savedInstanceState.getInt(KEY_QUOTE_INDEX);
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
//Display that text for the quote
mQuoteTextView = (TextView) findViewById(R.id.quoteTextView);
int quote = mQuoteList[mCurrentIndex].getQuote();
mQuoteTextView.setText(quote);
mQuoteTextView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
displayAuthorFact();
}
});
//Display the author of the quote
mAuthorTextView = (TextView) findViewById(R.id.authorTextView);
int author = mQuoteList[mCurrentIndex].getAuthor();
mAuthorTextView.setText(author);
mAuthorTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
displayAuthorFact();
}
});
//Display image
mImageView = (ImageView) findViewById(R.id.imageView);
mImageView.setImageResource(R.drawable.mountain_pic);
//set up listener to handle next button presses
mNextButton = (Button) findViewById(R.id.nextButton);
mNextButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
// move to the next quote in the list
//if index reaches end array,
//reset index to zero (first quote)
mCurrentIndex++;
if(mCurrentIndex == mQuoteList.length){
mCurrentIndex = 0;
}
updateQuote();
}
});
return v;
}
/** Display the quote at the current index. */
private void updateQuote(){
int quote = mQuoteList[mCurrentIndex].getQuote();
int author = mQuoteList[mCurrentIndex].getAuthor();
int picture = mQuoteList[mCurrentIndex].getPicture();
mQuoteTextView.setText(quote);
mAuthorTextView.setText(author);
mImageView.setImageResource(picture);
}
#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_quote, 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);
}
}
Create QuoteFragment
Copy-paste code from QuoteActivity
Remove setContent(R.layout.activity_quote) and implement onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) method
Initialize views in onViewCreated (View view, Bundle savedInstanceState) method
Rename activity_quote.xml to fragment_quote.xml
Create xml file activity_quote.xml and add the QuoteFragment as a content:
<fragment android:name="com.example.android.fragments.QuoteFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
See details here: http://developer.android.com/training/basics/fragments/creating.html#AddInLayout
And remove all code from QuoteActivity except of:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quote);
}
Related
I'm new to this and i'm doing an app for a university project and I wanted to put a VideoView in my app, so I watched this video ("https://www.youtube.com/watch?v=SrPHLj_q_OQ&t=421s") and did it and worked. But then I add to copy the code from content_main.xml to a fragment and it stopped working and giving an error on the "android:onClick" on the Button. And when I press CTRL+F1 to inspect it says this:
"Corresponding method handler'public void videoplay(android.view.View)' not found
Inspection info:The onClick attribute value should be the name of a method in this View's context to invoke when the view is clicked.This name must correspond to a public method that takes exactly one parameter of type View.
Must be a string value, using '\;' to escape characters such as '\n' or '\uxxxx' for a unicode character.
Issue id:OnClick "
Heres my xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="16dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
android:background="#003e6f"
android:orientation="vertical"
tools:context=".InicioFragment">
<VideoView
android:id="#+id/videoView"
android:layout_width="match_parent"
android:layout_gravity="center_horizontal"
android:layout_height="197dp" />
<Button
android:id="#+id/button2"
style="#style/Widget.AppCompat.Button.Borderless"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:background="#FF6600"
android:text="Play"
android:onClick="videoplay"
android:textColor="#ffffff" />
<ImageView
android:id="#+id/imagem2"
android:layout_width="match_parent"
android:layout_height="360dp"
android:layout_alignParentBottom="true"
android:adjustViewBounds="false"
android:background="#drawable/tech3" />
</LinearLayout>
Heres my java:
package intro.android.migueloliveiraapp;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.Toast;
import android.widget.VideoView;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
clk = (Button) findViewById(R.id.button2);
videov = (VideoView) findViewById(R.id.videoView);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//Carregar o layout do fragent incial "InicioFragment"
InicioFragment inicioFragment = new InicioFragment();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction()
.replace(R.id.relative_layout_para_o_fragment, inicioFragment, inicioFragment.getTag())
.commit();
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_oliveira) {
Quem_Oliveira quem_oliveiraFragment = new Quem_Oliveira();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction()
.replace(R.id.relative_layout_para_o_fragment,
quem_oliveiraFragment, quem_oliveiraFragment.getTag())
.commit();
Toast.makeText(this, "Oliveira", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_profissao) {
Profissao profissaoFragment = new Profissao();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction()
.replace(R.id.relative_layout_para_o_fragment,
profissaoFragment, profissaoFragment.getTag())
.commit();
Toast.makeText(this, "Profissão", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_feitos) {
Principais_feitos principais_feitosFragment = new Principais_feitos();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction()
.replace(R.id.relative_layout_para_o_fragment,
principais_feitosFragment, principais_feitosFragment.getTag())
.commit();
Toast.makeText(this, "Principais Feitos", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_academicas) {
Habilitacoes_Academicas habilitacoes_academicasFragment = new Habilitacoes_Academicas();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction()
.replace(R.id.relative_layout_para_o_fragment,
habilitacoes_academicasFragment, habilitacoes_academicasFragment.getTag())
.commit();
Toast.makeText(this, "Habilitações Académicas", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_galeria) {
Galeria galeriaFragment = new Galeria();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction()
.replace(R.id.relative_layout_para_o_fragment,
galeriaFragment, galeriaFragment.getTag())
.commit();
Toast.makeText(this, "Galeria", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_contactos) {
Contactos contactosFragment = new Contactos();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction()
.replace(R.id.relative_layout_para_o_fragment,
contactosFragment, contactosFragment.getTag())
.commit();
Toast.makeText(this, "Contactos", Toast.LENGTH_SHORT).show();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
//video view
Button clk;
VideoView videov;
public void videoplay(View v){
String videopath = "android.resource://intro.android.migueloliveiraapp/" + R.raw.oliveira;
Uri uri = Uri.parse(videopath);
videov.setVideoURI(uri);
videov.start();
}
}
Heres my InicioFragment java:
package intro.android.migueloliveiraapp;
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.
*/
public class InicioFragment extends Fragment {
public InicioFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_inicio, container, false);
}
}
heres my updated InicioFragment.java:
package intro.android.migueloliveiraapp;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.net.Uri;
import android.widget.Button;
import android.widget.VideoView;
/**
* A simple {#link Fragment} subclass.
*/
public class InicioFragment extends Fragment {
public InicioFragment() {
// Required empty public constructor
}
#Override
public View onCreateView (LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_inicio, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
clk = (Button) view.findViewById(R.id.button);
videov = (VideoView) view.findViewById(R.id.videoView);
// bind the views here.
Button button2 = view.findViewById(R.id.button);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// do something here.
}
});
}
Button clk;
VideoView videov;
public void videoplay(View v){
String videopath = "android.resource://intro.android.migueloliveiraapp/" + R.raw.oliveira;
Uri uri = Uri.parse(videopath);
videov.setVideoURI(uri);
videov.start();
}
}
You can use this for click.
Button mPlayVideo;
//In oncreate
mPlayVideo = findViewById(R.id.button2);
mPlayVideo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Clicked", Toast.LENGTH_SHORT).show();
}
});
In your xml your tools:context=".InicioFragment refers to your fragment and not your activity.
Your method is found inside the activity and not the fragment class and this is why are getting this error.
You can check Call an activity method from a fragment
But I can recommend using the onClick attribute inside your activities and inside fragment use normal click listener:
View view = findViewById(R.id.viewId);
view .setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do something
}
});
This is because you created videoplay() method inside your MainActivity.java . You should put your videoplay() method into the InicioFragment.java as it is the corresponding file for the xml layout you have mentioned above.
Initialize your variables like bellow inside your onCreateView method on InicioFragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_inicio, container, false);
Button btn1 = view.findViewById(R.id.button_id);
.....
.....
return view;
}
public void videoplay(View v){
.........
.....
}
The following error:
"Corresponding method handler'public void videoplay(android.view.View)' not found
Inspection info:The onClick attribute value should be the name of a method in this View's context to invoke when the view is clicked.This name must correspond to a public method that takes exactly one parameter of type View.
Must be a string value, using '\;' to escape characters such as '\n' or '\uxxxx' for a unicode character.
Issue id:OnClick "
means that you forget to add the corresponding method in your Activity class when using android:onClick="videoplay" attribute. So, you need to add the following method to your activity:
public void videoplay(View v){
// do something here.
}
The most important part is, android:onClick tag is only working when you're using it inside the content layout of Activity.. So, android:onClick doesn't work when you're using it inside the fragment layout. You need to use the onClickListener instead.
You need to bind the view and add the onClickListener with something like this:
public class InicioFragment extends Fragment {
public InicioFragment() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_inicio, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// bind the views here.
Button button2 = view.findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// do something here.
}
});
}
}
Pay attention on your xml file that this file's context is your InicioFragment (tools:context=".InicioFragment" )
Therefore, videoplay(View v) should be inside your InicioFragment class.
That's the reason why is not found. It won't search on your MainActivity.
public class InicioFragment extends Fragment {
public InicioFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.testclassfragment, container, false);
Button clk = (Button) view.findViewById(R.id.button);
VideoView videov = (VideoView) view.findViewById(R.id.videoView);
return view;
}
public void videoplay(View v){
String videopath = "android.resource://intro.android.migueloliveiraapp/" + R.raw.oliveira;
Uri uri = Uri.parse(videopath);
videov.setVideoURI(uri);
videov.start();
}
}
Since you also have a variable for your button another option is to do:
clk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("TESTING", "Clicked");
}
});
My first thread here - sorry if the text formatting is bad.
I use Android Studio 3.1.3 API27 and work on an app for Smartphone.
The app currently consists of 1 activity (split in 3 fragments), a second activity and 5 xml files.
By using a ViewPager, I'm able to swipe through the 3 fragments.
The 2nd fragment (middle fragment) contains 2 buttons that each open the 2nd activity, which contains many color buttons.
When clicking on the color buttons, I can change the background colors of the 1st fragment.
After choosing a color, the 2nd activity gets closed and I'm back in activity 1 -> fragment2.
It works, but the PROBLEM is that I always have to swipe to the 3rd fragment,
then back to the 2nd and then to the 1st.
If I don't do this, the colors of fragment 1 will remain the old ones.
Now I'm looking for a way to update the layout of fragment 1 as soon as I press a color button of activity 2.
I already tried this:
when writing the SharedPreferences (Activity2), I use editor.apply() instead of editor.commit()
when reading the SharedPreferences (Activity1 -> Fragment1), I use Context.MODE_MULTI_PROCESS instead of Context.MODE_PRIVATE
using viewpage.setOffscreenPageLimit(0); in the MainActivity inside of my public void SetUpViewPager(ViewPager viewpage) method.
Nothing helped, though.
This is how it looks like:
MainActivity.java (Activity 1):
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity
{
ViewPager vp;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager vp = findViewById(R.id.vp);
SetUpViewPager(vp);
}
public void SetUpViewPager(ViewPager viewpage)
{
MyViewPagerAdapter Adapter = new MyViewPagerAdapter(getSupportFragmentManager());
Adapter.AddPageFragment(new Page_1(), "Page 1");
Adapter.AddPageFragment(new Page_2(), "Page 2");
Adapter.AddPageFragment(new Page_3(), "Page 3");
viewpage.setOffscreenPageLimit(0);
viewpage.setAdapter(Adapter);
}
public class MyViewPagerAdapter extends FragmentPagerAdapter
{
private List<Fragment> MyFragment = new ArrayList<>();
private List<String> MyPageTitle = new ArrayList<>();
public MyViewPagerAdapter(FragmentManager manager)
{
super(manager);
}
public void AddPageFragment(Fragment Frag, String Title)
{
MyFragment.add(Frag);
MyPageTitle.add(Title);
}
#Override
public Fragment getItem(int i)
{
return MyFragment.get(i);
}
#Nullable
#Override
public CharSequence getPageTitle(int position)
{
return MyPageTitle.get(position);
}
#Override
public int getCount()
{
return 3;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
int id = item.getItemId();
if (id == R.id.action_settings)
{
return true;
}
return super.onOptionsItemSelected(item);
}
}
Page_1.java (Activity 1 -> Fragment 1):
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import static android.content.Context.MODE_PRIVATE;
public class Page_1 extends Fragment
{
int backgroundColorLeft, backgroundColorRight, textColorLeft, textColorRight; // Variables for SharedPreferences
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View PageOne = inflater.inflate(R.layout.page1, container, false); // Link view to layout?
return PageOne;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState)
{
SharedPreferences prefs = getActivity().getSharedPreferences("bgColor", Context.MODE_MULTI_PROCESS); // Load saved shared file
backgroundColorLeft = prefs.getInt("backgroundColorLeft", backgroundColorLeft); // Load saved background color for left layout
textColorLeft = prefs.getInt("textColorLeft", textColorLeft); // Load saved text color for left layout
backgroundColorRight = prefs.getInt("backgroundColorRight", backgroundColorRight); // Load saved background color for right layout
textColorRight = prefs.getInt("textColorRight", textColorRight); // Load saved text color for right layout
RelativeLayout relLayoutLeft = getActivity().findViewById(R.id.rel_layout_left); // Link variable to ID of left layout
relLayoutLeft.setBackgroundColor(backgroundColorLeft); // Change background color of left layout
TextView tvLeft = getActivity().findViewById(R.id.tv_left); // Link variable to ID
tvLeft.setTextColor(textColorLeft); // Change text color of left layout
RelativeLayout relLayoutRight = getActivity().findViewById(R.id.rel_layout_right); // Link variable to ID of right layout
relLayoutRight.setBackgroundColor(backgroundColorRight); // Change background color of right layout
TextView tvRight = getActivity().findViewById(R.id.tv_right); // Link variable to ID
tvRight.setTextColor(textColorRight); // Change text color of right layout
super.onActivityCreated(savedInstanceState);
}
}
Page_2.java (Activity 1 -> Fragment 2):
package com.example.konstantin.clipcodes_swiping;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import static android.content.Context.MODE_PRIVATE;
public class Page_2 extends Fragment
{
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View PageTwo = inflater.inflate(R.layout.page2, container, false);
Button buttonLeft = PageTwo.findViewById(R.id.button_left); // Link variable to ID of left button
buttonLeft.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
int pos = 1; // Set position to left
setPosition(pos); // Load setColor method and send 2 color values
}
});
Button buttonRight = PageTwo.findViewById(R.id.button_right); // Link variable to ID of right button
buttonRight.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
int pos = 2; // Set position to right
setPosition(pos); // Load setColor method and send 2 color values
}
});
return PageTwo;
}
public void setPosition (int pos) // Start second activity to choose colors
{
Intent intentPos = new Intent(getActivity(), Page_4_Colors.class); // Create intent for current Activity and target activity
SharedPreferences prefs = getActivity().getSharedPreferences("bgColor", Context.MODE_MULTI_PROCESS); // Create new SharedPreferences instance
SharedPreferences.Editor editor = prefs.edit(); // Assign variable to editor function
editor.putInt("position", pos); // Write selected position (int) inside of editor
editor.apply(); // Save values, close process
getActivity().startActivity(intentPos); // Start second activity
}
}
Page_3.java (Activity 1 -> Fragment 3):
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Page_3 extends Fragment
{
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View PageThree = inflater.inflate(R.layout.page3, container, false);
return PageThree;
}
}
Page_4_Colors.java (Activity 2):
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class Page_4_Colors extends Activity
{
int pos;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.page4_colors);
SharedPreferences prefs = getSharedPreferences("bgColor", MODE_MULTI_PROCESS); // Load saved shared file
pos = prefs.getInt("position", pos); // Load saved position (int)
Log.wtf("Position", String.valueOf(pos)); // Show pos value in Log
Button buttonWhite = findViewById(R.id.button_white);
buttonWhite.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
setColor(getResources().getColor(R.color.white), getResources().getColor(R.color.black)); // Load setColor method and send 2 color values
}
});
Button buttonYellow = findViewById(R.id.button_yellow);
buttonYellow.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
setColor(getResources().getColor(R.color.yellow), getResources().getColor(R.color.black)); // Load setColor method and send 2 color values
}
});
Button buttonOrange = findViewById(R.id.button_orange);
buttonOrange.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
setColor(getResources().getColor(R.color.orange), getResources().getColor(R.color.black)); // Load setColor method and send 2 color values
}
});
Button buttonRed = findViewById(R.id.button_red);
buttonRed.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
setColor(getResources().getColor(R.color.red), getResources().getColor(R.color.black)); // Load setColor method and send 2 color values
}
});
Button buttonGreen = findViewById(R.id.button_green);
buttonGreen.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
setColor(getResources().getColor(R.color.green), getResources().getColor(R.color.black)); // Load setColor method and send 2 color values
}
});
Button buttonBlue = findViewById(R.id.button_blue);
buttonBlue.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
setColor(getResources().getColor(R.color.blue), getResources().getColor(R.color.white)); // Load setColor method and send 2 color values
}
});
}
public void setColor (int backgroundColor, int textColor) // Write color values into SharedPreferences
{
SharedPreferences prefs = getSharedPreferences("bgColor", MODE_MULTI_PROCESS); // Create new SharedPreferences instance
SharedPreferences.Editor editor = prefs.edit(); // Assign variable to editor function
if (pos == 1)
{
editor.putInt("backgroundColorLeft", backgroundColor); // Write background color (int) inside of editor
editor.putInt("textColorLeft", textColor); // Write text color (int) inside of editor
}
if (pos == 2)
{
editor.putInt("backgroundColorRight", backgroundColor); // Write background color (int) inside of editor
editor.putInt("textColorRight", textColor); // Write text color (int) inside of editor
}
editor.apply(); // Save values, close process
this.finish(); // Close this activity
}
}
Thanks for any help!
use EventBus
unregister and register EventBus in Page_1 onStop() and onStart()
EventBus.getDefault().unregister(this)
EventBus.getDefault().register(this)
and use this for post the value
EventBus.getDefault().post(new MessageEvent("Change Color"));
and this function will handle the MessageEvent
#Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MessageEvent event) {
//change the color here
//add this function in Page_1
}
when you update the value of color. put in MessageEvent documentation
You can update the UI (or at least the color related part) for each fragment in the onResume() method, thus, when you return from the second activity, it will refresh.
When a Fragment is made visible (i.e., the selected page in your ViewPager), its setUserVisibleHint() method is called. You can override that method in your Fragment and use it to trigger a refresh.
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if(isVisibleToUser){
//you can check if the color is changed then refresh the fragment if not then don't do anything
//here you should refresh your fragment , this will called every time you
//view this fragment in all cases even if you didn't move to the
//third tab
}
}
How To Refresh A Fragment
Fragment currentFragment = getFragmentManager().findFragmentByTag("YourFragmentTag");
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.detach(currentFragment);
fragmentTransaction.attach(currentFragment);
fragmentTransaction.commit();
To start, and via exhaustive searching I have found that most people have this error due to improper imports of the Fragment class instead of using the support library.
I on the other hand am following a tutorial located here.
My code is essentially identical to his but I will attach my MainActivity and TimePickerDialogFragment below. The tutorial I'm following is dated August 2012 which is likely the reason I'm running into this, I could just swap tutorials but I'd really like the debug experience of correcting this and the reason as to why its occuring.
The error occurs with the code //add the fragment object to the fragment transaction
ft.add(timePicker, "time_picker");
Here is my MainActivity:
package com.stembo.android.timepickerdialogdemo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends FragmentActivity {
int mHour = 15;
int mMinute = 15;
//This handles the message send from TimePickerDialogFragment (TPDF)
Handler mHandler = new Handler(){
#Override
public void handleMessage(Message m){
//create a bundle object to pass the current set time
Bundle b = m.getData();
//getting the hour of day from bundle
mHour = b.getInt("set_hour");
//getting the minute from bundle
mMinute = b.getInt("set_minute");
//displaying a short time message containing the time set by the TPDF
Toast.makeText(getBaseContext(), b.getString("set_time"),Toast.LENGTH_LONG).show();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
//click event handler for button
OnClickListener listener = new OnClickListener() {
#Override
public void onClick(View v) {
//create a bundle object to pass current time set
Bundle b = new Bundle();
//add currently set hour to bundle object
b.putInt("set_hour", mHour);
//add currently set minute to bundle object
b.putInt("set_minute", mMinute);
//instantiate TPDF
TimePickerDialogFragment timePicker = new TimePickerDialogFragment(mHandler);
//setting the bundle object on timepicker fragment
timePicker.setArguments(b);
//get a fragment manager for this activity
FragmentManager fm = getSupportFragmentManager();
//start a fragment transaction
FragmentTransaction ft = fm.beginTransaction();
//add the fragment object to the fragment transaction
ft.add(timePicker, "time_picker");
//opening the timepicker fragment
ft.commit();
}
};
//get an instance of Set button
Button btnSet = (Button)findViewById(R.id.btnSet);
btnSet.setOnClickListener(listener);
}
#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_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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I don't think its needed, but here is the TimePickerDialogFragment
package com.stembo.android.timepickerdialogdemo;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TimePicker;
/**
* Created by myxom on 16/02/16.
*/
public class TimePickerDialogFragment extends DialogFragment {
Handler mHandler ;
int mHour;
int mMinute;
//public TimePickerDialogFragment(){}; //solves a lint issue
public TimePickerDialogFragment(Handler h){ //another lint issue
/** Getting the reference to the message handler instantiated in MainActivity class */
mHandler = h;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState){
/** Creating a bundle object to pass currently set time to the fragment */
Bundle b = getArguments();
/** Getting the hour of day from bundle */
mHour = b.getInt("set_hour");
/** Getting the minute of hour from bundle */
mMinute = b.getInt("set_minute");
TimePickerDialog.OnTimeSetListener listener = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
mHour = hourOfDay;
mMinute = minute;
/** Creating a bundle object to pass currently set time to the fragment */
Bundle b = new Bundle();
/** Adding currently set hour to bundle object */
b.putInt("set_hour", mHour);
/** Adding currently set minute to bundle object */
b.putInt("set_minute", mMinute);
/** Adding Current time in a string to bundle object */
b.putString("set_time", "Set Time : " + Integer.toString(mHour) + " : " + Integer.toString(mMinute));
/** Creating an instance of Message */
Message m = new Message();
/** Setting bundle object on the message object m */
m.setData(b);
/** Message m is sending using the message handler instantiated in MainActivity class */
mHandler.sendMessage(m);
}
};
/** Opening the TimePickerDialog window */
return new TimePickerDialog(getActivity(), listener, mHour, mMinute, false);
}
}
The problem is with you TimePickerDialogFragment.java
Replaceimport android.app.DialogFragment withimport android.support.v4.app.DialogFragment;
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I just starting learning to develop an android app and for that i followed google's basic tutorial.
In the tutorial there is simply a textbox and a button. On pressing the button it takes the text from the textbox and displays it in another activity. But somehow the button isn't working for me.
Here is the code for the fragment_main.xml, MainActivity.java and DisplayMessageActivity.java. I just want to know if i am doing something wrong or if i am missing something.
fragmant_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<EditText android:id="#+id/edit_message"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="#string/edit_message" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_send"
onClick="sendMessage" />
</LinearLayout>
MainActivity.java:
package com.example.first;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
public class MainActivity extends ActionBarActivity {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
#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();
}
}
#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;
}
}
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
DisplayMessageActivity.java
package com.example.first;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class DisplayMessageActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
}
#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_message, 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_message,
container, false);
return rootView;
}
}
}
EDIT **
In your fragment_main.xml file the the last line of your Button tag should be : android:onClick="sendMessage" instead of onClick="sendMessage"
I created a Main activity, which sends me to an ActiviteResultats activity.
My goal is now just to show a message in this activity (Message who come from the main).
I followed the Starting Another Activity tutorial.
The problem is, when I start the ActiviteResultats activity, I have an error:
"no view found for id 0x7f080000 ........... for fragment PlaceholderFragment"
... and the app shuts down.
I don't know yet how to use fragments, and the tutorial says I don't have to use it for this example.
Where am I going wrong?
My code :
package com.example.surveyor;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class ActiviteResultats extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activite_resultats);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
String message = "TODO";
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activite_resultats, 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_activite_resultats, container, false);
return rootView;
}
}
}
I had the same problem. Just remove the part:
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
That solved it for me. Hope that helps!
A quick look over the tutorial shows that most of the Fragment code is removed in a later step. You could remove all the code related to the fragments, along with the bit about the options menu if you want to clear out all distractions. It's likely to solve your problem and isn't vital to that tutorial
What you need to do is to set up intent in your main activity, and then get it here so it goes like follows:
under Main_Activity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.Main_Activity);
Intent i = new Intent(this,activiteResultats.class); // or getApplicationContext() <= for context
i.putExtras("TagOfMyMessage","MyMessageblablabla");
startActivity(i);
}
under ActivteResultats.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activite_resultats);
Intent i = getIntent();
String message = i.getStringExtras(); // or something like it
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
}
You just don't need to use fragments if you want a clear and easy tutorial i advice you to check this one : http://www.vogella.com/tutorials/AndroidIntent/article.html