Create Button In A Fragment - java

Hello Im new to android i want to ask how do i do intent inside the fragment layout
any answers i would really appreciate
here is the code :
for HomeFragment.java
package com.example.splashscreen;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.net.wifi.hotspot2.pps.HomeSp;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import com.denzcoskun.imageslider.ImageSlider;
import com.denzcoskun.imageslider.constants.ScaleTypes;
import com.denzcoskun.imageslider.models.SlideModel;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {#link Fragment} subclass.
* Use the {#link HomeFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class HomeFragment extends Fragment implements View.OnClickListener {
// Initiate
Button button;
View rootView;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public HomeFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment HomeFragment.
*/
// TODO: Rename and change types and number of parameters
public static HomeFragment newInstance(String param1, String param2) {
HomeFragment fragment = new HomeFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#SuppressLint("WrongViewCast")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/**Button btnMoveActivity = (Button) rootView.findViewById(R.id.btn1);
btnMoveActivity.setOnClickListener((View.OnClickListener) this);
ImageSlider imageSlider = getActivity().findViewById(R.id.image_slider);
List<SlideModel> slideModel=new ArrayList<>();
slideModel.add(new SlideModel(R.drawable.kucing2, ScaleTypes.FIT));
slideModel.add(new SlideModel(R.drawable.kucing1,ScaleTypes.FIT));
slideModel.add(new SlideModel(R.drawable.kucing2,ScaleTypes.FIT));
imageSlider.setImageList(slideModel,ScaleTypes.FIT);
**/
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_home, container, false);
return inflater.inflate(R.layout.fragment_home, container, false);
}
public void onViewCreated(View view,Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
button = (Button) rootView.findViewById(R.id.btn1);
button.setOnClickListener(view1 -> {
switch (view1.getId()){
case R.id.btn1:
Intent moveIntent = new Intent(MainActivity.this,MoveActivity.class); // my button isn't working here
startActivity(moveIntent);
break;
}
});
}
#Override
public void onClick(View view) {
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.splashscreen">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.Splashscreen">
<activity
android:name=".Splashscreen"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity">
</activity>
</application>
</manifest>
my button cant do intent and i've try several methods that i cant understand i want to add image slider later but I prefer the button first
thank you for your valuable answer

I'm not sure if this would work in your case, but if you want to access the fragment's host activity and use it for that Intent you can try this
Activity myParentActivity = (MainActivity) getActivity();
Intent moveIntent = new Intent(myParentActivity, MoveActivity.class);
or this
Activity myParentActivity = (MainActivity) requireActivity();
Intent moveIntent = new Intent(myParentActivity, MoveActivity.class);
put this in your AndroidManifest.xml
<activity android:name=".MoveActivity"/>

Related

E/RecyclerView: No adapter attached; Skipping layout ERROR Android Studio with API 29 [duplicate]

This question already has answers here:
recyclerview No adapter attached; skipping layout
(38 answers)
Closed 1 year ago.
So I was following a video to do a news app from scratch in Android Studio and I encountered the error of the title. I tried to follow many of the answers in questions about the same error but its hard to understand because everyone has different codes as I spected. So here is my Adapter code:
package com.example.newsapp4;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import com.example.newsapp4.Model.Articles;
import com.squareup.picasso.Picasso;
import java.util.List;
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
Context context;
List<Articles> articles;
public Adapter(Context context, List<Articles> articles) {
this.context = context;
this.articles = articles;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.items, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
final Articles a = articles.get(position);
String imageUrl = a.getUrlToImage();
holder.tvTitle.setText(a.getTitle());
holder.tvSource.setText(a.getSource().getName());
holder.tvDate.setText(a.getPublishedAt());
Picasso.with(context).load(imageUrl).into(holder.imageView);
}
#Override
public int getItemCount() {
return articles.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView tvTitle,tvSource,tvDate;
ImageView imageView;
CardView cardView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
tvTitle = itemView.findViewById(R.id.tvTitle);
tvSource = itemView.findViewById(R.id.tvSource);
tvDate = itemView.findViewById(R.id.tvDate);
imageView = itemView.findViewById(R.id.image);
cardView = itemView.findViewById(R.id.cardView);
}
}
}
And here is my java class where I call the adapter with the recyclerview:
package com.example.newsapp4;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import com.example.newsapp4.Model.Articles;
import com.example.newsapp4.Model.Headlines;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class sportsnews extends AppCompatActivity {
Adapter adapter;
Intent intencion;
RecyclerView recyclerView;
final String API_KEY = "my api key";
List<Articles> articles = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sportsnews);
recyclerView = findViewById(R.id.recyclerView1);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
String country = getCountry();
retrieveJson(country, API_KEY);
}
public void retrieveJson(String country, String apiKey){
Call<Headlines> call = ApiClient.getInstance().getApi().getHeadlines(country, apiKey);
call.enqueue(new Callback<Headlines>() {
#Override
public void onResponse(Call<Headlines> call, Response<Headlines> response) {
if(response.isSuccessful() && response.body().getArticles() != null){
articles.clear();
articles = response.body().getArticles();
adapter = new Adapter(sportsnews.this,articles);
recyclerView.setAdapter(adapter);
}
}
#Override
public void onFailure(Call<Headlines> call, Throwable t) {
Toast.makeText(sportsnews.this, t.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
});
}
public String getCountry(){
Locale locale = Locale.getDefault();
String country = locale.getCountry();
return country.toLowerCase();
}
public void aPerfil(View vista){
intencion = new Intent(this, profile_activity.class);
startActivity(intencion);
}
}
Notice that there is a method that goes with a button that is not applicated. The method is aPerfil.
This here is my manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.newsapp4">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".sportsnews" android:screenOrientation="locked"/>
<activity android:name=".profile_activity" android:screenOrientation="locked"/>
<activity android:name=".menuContent" android:screenOrientation="locked"/>
<activity android:name=".MainActivity" android:screenOrientation="locked">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="preloaded_fonts"
android:resource="#array/preloaded_fonts" />
</application>
</manifest>
There are more activities before reaching the one that has the adapter.
Im guessing that in my api key I need to put the key that the webpage give me, something like a lot of numbers and letters, not a link.
Feel free to ask for more code if you need it.
Thanks for your time!
move below code from onResponse to onCreate before retrieveJson(country, API_KEY);
adapter = new Adapter(sportsnews.this,articles);
recyclerView.setAdapter(adapter);
Create a setter in your Adapter something like below
public void setArticles(List<Articles> newArticle) {
if (newArticle != null && newArticle.size() > 0) {
this.articles = newArticle;
notifyDataSetChanged();
}
}
Then in your onResponse write something like below where earlier you were setting adapter in recylerview.
adapter.setArticles(articles)
Note: recylerView should always be attached to adapter when its inflating, you just cannot wait for API response because that runs on diff thread and will take time to fetch data till that time, OS will already try to inflate the recylerview and will fail if there is no adapter attached.
So we should always attach the adapter even with empty data as that is not the problem you can pass the data when you received it from API and then call notifyDataSetChanged() and then the adapter will take care of inflating each item.

How to open an activity using GridView. Android

I have a problem when opening a new activity, when clicking on element 0 sends me the activity but this does not show the content and does not send me some error, and adds the new activity in androidManifest.xml.
I will leave my code:
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.ivann.diuxgridmain" >
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme" >
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".leon">
</activity>
</application>
</manifest>
MainActivity.java
package com.example.ivann.diuxgridmain;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
GridView androidGridView;
String[] gridViewString = {
"Leon1", "Ave1", "Perro1", "Cara1", "Corazòn1", "Enojado1",
"Leon2", "Ave2", "Perro2", "Cara2", "Corazòn2", "Enojado2",
"Leon3", "Ave3", "Perro3", "Cara3", "Corazòn3", "Enojado3",
} ;
int[] gridViewImageId = {
R.drawable.leon, R.drawable.bird, R.drawable.cachorro, R.drawable.fb, R.drawable.heart, R.drawable.angry,
R.drawable.leon, R.drawable.bird, R.drawable.cachorro, R.drawable.fb, R.drawable.heart, R.drawable.angry,
R.drawable.leon, R.drawable.bird, R.drawable.cachorro, R.drawable.fb, R.drawable.heart, R.drawable.angry,
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CustomGridViewActivity adapterViewAndroid = new CustomGridViewActivity(MainActivity.this, gridViewString, gridViewImageId);
androidGridView=(GridView)findViewById(R.id.grid_view_image_text);
androidGridView.setAdapter(adapterViewAndroid);
androidGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int i, long id) {
Intent intent=null;
switch (i){
case 0:
// I think here is the error *******
intent = new Intent(MainActivity.this, leon.class);
startActivity(intent);
break;
}
Toast.makeText(MainActivity.this, "GridView Item: " + gridViewString[+i ], Toast.LENGTH_LONG).show();
}
});
}
}
leon.java
package com.example.ivann.diuxgridmain;
import android.app.Activity;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
/**
* Created by ivann on 09/06/2017.
*/
public class leon extends Activity {
#Override
public void onCreate(Bundle savedInstanceState, #Nullable PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
setContentView(R.layout.leonactividad);
}
}
just remove
this
#Override
public void onCreate(Bundle savedInstanceState, #Nullable PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
setContentView(R.layout.leonactividad);
}
with
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.leonactividad);
}
Because you use also PersistableBundle in onCreate method and PersistableBundle use from API Level 21. So you can replace onCreate method as below:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.leonactividad);
}
Button or ImageButton has a higher priority level than itemView. If your item view contains those, it might be the reason, and you can use TextView/ImageView instead.

Android - by clicking instead of going forward is back to the previous page

I use Android Studio, created four new activity each button. I try every button leads to the next page.
After I attach all the buttons I run the app and it really works.
When I press the button on the first page it takes me to the second page, but when I press the button on the second page to go to the third, it takes me back to the first page.
first activity:
package liranbenzino.kids;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View viewBtnClick) {
// link to class
Intent intent = new Intent(MainActivity.this,Main2Activity.class);
startActivity(intent);
}});
}}
second activity:
package liranbenzino.kids;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class Main2Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View viewBtnClick1) {
// link to class
Intent intent = new Intent(Main2Activity.this,Main3Activity.class);
startActivity(intent);
}});
}
}
thied activity:
package liranbenzino.kids;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class Main3Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
findViewById(R.id.button3).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View viewBtnClick) {
// link to class
Intent intent = new Intent(Main3Activity.this,Main4Activity.class);
startActivity(intent);
}});
}
}
four activity:
package liranbenzino.kids;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
import android.view.View;
public class Main4Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main4);
findViewById(R.id.button4).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View viewBtnClick) {
Toast.makeText(Main4Activity.this,"NAME", Toast.LENGTH_LONG).show();
}});
}}
AndroidMenifest.xml :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="liranbenzino.kids">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Main2Activity" />
<activity android:name=".Main3Activity" />
<activity android:name=".Main4Activity"></activity>
</application>
</manifest>
thank'S
Your code is ok
How your decide that you back to firstPage when your click 2nd activity button. your code is ok.. use label in each page. then try ...
May be your some button label is same and you become confuse in which page you are in..
You can change your button label as First_Page_Button,Second_Page_Button,Third_Page_Button etc to decide in which page you are...
in each activity change the INTENT name for example in activity2 change
Intent intent = new Intent(Main2Activity.this,Main3Activity.class);
startActivity(intent);
to
Intent intent2 = new Intent(Main2Activity.this,Main3Activity.class);
startActivity(intent2);

How do i display a new list after another list in Android [closed]

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 7 years ago.
Improve this question
Say were talking about body parts and workouts.
I want to show the chest when its clicked it shows a list of workouts:
String[] bodyPart = { "Chest"};
String[] chestsWorkout = {"Bench", "Pushups", "Pullups",
"Incline bench", "Decline bench"};
There is very simple way to do it. You can put many options along with chest in that string array bodyPart and you can create relevant string array like chestsWorkout for particular bodyPart. You can check which bodyPart user has clicked and then you can pass relevant string array like chestsWorkout with intent.
MainActivity.java
package com.example.opnanotherlistexample;
import java.util.ArrayList;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends ActionBarActivity {
String[] bodyPart = { "Chest", "Legs" };
String[] chestsWorkout = { "Bench", "Pushups", "Pullups", "Incline bench",
"Decline bench" };
String[] legsWorkout = { "walk", "run"};
private ListView listNew;
private ArrayList<String> newarraylist;
private ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listNew = (ListView) findViewById(R.id.listNew);
newarraylist = new ArrayList<String>();
for (int i = 0; i < bodyPart.length; i++) {
newarraylist.add(bodyPart[i]);
}
adapter = new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_dropdown_item_1line, newarraylist);
listNew.setAdapter(adapter);
listNew.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view,
int position, long id) {
// TODO Auto-generated method stub
String clickedItem = newarraylist.get(position).toString();
Intent intent = new Intent(MainActivity.this,
SecondActivity.class);
if(clickedItem.toLowerCase().equals("chest")){
intent.putExtra("parameters", chestsWorkout);
}else if(clickedItem.toLowerCase().equals("legs")){
intent.putExtra("parameters", legsWorkout);
}
startActivity(intent);
}
});
}
}
SecondActivity.java
package com.example.opnanotherlistexample;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class SecondActivity extends Activity {
private ListView listAnother;
private ArrayAdapter<String> adapter;
private ArrayList<String> arraylist;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.secondactivity);
listAnother = (ListView) findViewById(R.id.listAnother);
if (getIntent().hasExtra("parameters")) {
String[] params = getIntent().getStringArrayExtra("parameters");
arraylist = new ArrayList<String>();
for (int i = 0; i < params.length; i++) {
arraylist.add(params[i]);
Log.e("balvier", params[i]);
}
adapter = new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_dropdown_item_1line, arraylist);
listAnother.setAdapter(adapter);
}
}
}
opnanotherlistexample manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.opnanotherlistexample"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivity" />
</application>
</manifest>

mDrawer can't work on android >3

I builded an app with simply webview and mDrawer slide menu. But after seeing that it's not working on > 3 android i have added a support library and made some changes but it's still not working.
here is the code
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentManager.OnBackStackChangedListener;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnKeyListener;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
#SuppressLint("NewApi")
public class MainActivity extends ActionBarActivity {
private LayoutInflater mInflater;
private DrawerLayout mDrawerLayout;
WebView browser;
// ListView represents Navigation Drawer
private ListView mDrawerList;
// ActionBarDrawerToggle indicates the presence of Navigation Drawer in the action bar
private ActionBarDrawerToggle mDrawerToggle;
private String mTitle = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView browser = (WebView) findViewById(R.id.webView1);
browser.loadUrl("");
browser.setWebViewClient(new WebViewClient());
WebSettings webSettings = browser.getSettings();
webSettings.setJavaScriptEnabled(true);
mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.drawer_list);
// Getting reference to the ActionBarDrawerToggle
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_close) {
/** Called when drawer is closed */
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitle);
invalidateOptionsMenu();
}
/** Called when a drawer is opened */
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle("Menu");
invalidateOptionsMenu();
}
};
browser.setOnKeyListener(new OnKeyListener()
{
public boolean onKey(View v, int keyCode, KeyEvent event)
{
if(event.getAction() == KeyEvent.ACTION_DOWN)
{
WebView webView = (WebView) v;
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
if(webView.canGoBack())
{
webView.goBack();
return true;
}
break;
}
}
return false;
}
});
// Setting DrawerToggle on DrawerLayout
mDrawerLayout.setDrawerListener(mDrawerToggle);
// Creating an ArrayAdapter to add items to the listview mDrawerList
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getBaseContext(),
R.layout.drawer_list_item, getResources().getStringArray(R.array.menus));
// Setting the adapter on mDrawerList
mDrawerList.setAdapter(adapter);
// Enabling Home button
getSupportActionBar().setHomeButtonEnabled(true);
// Enabling Up navigation
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// Setting item click listener for the listview mDrawerList
mDrawerList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Getting an array of rivers
String[] menuItems = getResources().getStringArray(R.array.menus);
// Currently selected river
mTitle = menuItems[position];
// Creating a fragment object
// Passing selected item information to fragment
Bundle data = new Bundle();
data.putInt("position", position);
data.putString("url", getUrl(position));
// Getting reference to the FragmentManager
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.addOnBackStackChangedListener(new OnBackStackChangedListener() {
public void onBackStackChanged() {
if(getSupportFragmentManager().getBackStackEntryCount() == 0)
finish();
}
});
// Creating a fragment transaction
FragmentTransaction ft = fragmentManager.beginTransaction();
// Adding a fragment to the fragment transaction
// Committing the transaction
ft.commit();
// Closing the drawer
mDrawerLayout.closeDrawer(mDrawerList);
}
});
}
I have tried to change getActionBar() to getSupportActionBar() but i got next error:
The method getSupportActionBar() is undefined for the type new ActionBarDrawerToggle(){}
Logcat:
04-03 14:39:29.237: E/AndroidRuntime(687): FATAL EXCEPTION: main
04-03 14:39:29.237: E/AndroidRuntime(687): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.com/com.example.com.MainActivity}: java.lang.ClassNotFoundException: com.example.com.MainActivity in loader dalvik.system.PathClassLoader[/data/app/com.example.com-2.apk]
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.com"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
android:allowBackup="true"
android:icon="#drawable/icon"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.com.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
If you have not added these two functions in your code, then add it and try. It will work.
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return false;
}

Categories